Way#1
Use Callable
instead, and get this string from a Future
.
Check here for an example which returns a String
Like this:
public class GetDataCallable implements Callable<String> {
@Override
public String call() throws Exception {
return getDataFromRemote(); //get from file and returns
}
}
and you use something like
GetDataCallable <String> task = new GetDataCallable <String>();
ExecutorService service = Executors.newFixedThreadPool(1);
Future<String> future =service.submit(task);//run the task in another thread,
..//do any thing you need while the thread is runing
String data=future.get();//Block and get the returning string from your Callable task
If you insist using Thread
, you can try the below 2 ways
Way#2
public youThread extends Thread{
private String data;//this is what you need to return
@Override
public void run(){
this.data=//get from remote file.
}
public String getData(){
return data;
}
}
But you have to make sure the thread completes before you call getData(), for example , you can use thread.join() to do that.
thread.start()
..//some jobs else
thread.join();
String data=thread.getData();
Way#3
Use some static callback method at the end of your run()
Say
public Class StoreDataCallback{
public static void storeData(String data_from_thread){
objectCan.setData(data_from_thread);//get access to your data variable and assign the value
}
}
public Class YourThread extends Thread{
@Override
public void run(){
String data =getDataFromRemote();//do some thing and get the data.
StoreDataCallback.storeData(data);
}
}