我正在编写一个在单独线程上读取远程文件数据的类。
该类继承自thread,在run方法中读取一些远程文件数据。我将数据存储在一个字符串中。
我可以添加其他返回此数据字符串的方法吗?
我看到 isalive 在 run 方法返回后返回 false 值。
我需要使用事件机制吗?
请提出一些更好的解决方法。
最佳答案
方式#1
在此处查看 example它返回一个字符串
像这样:
public class GetDataCallable implements Callable<String> {
@Override
public String call() throws Exception {
return getDataFromRemote(); //get from file and returns
}
}
你使用类似的东西
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
如果你坚持使用Thread
,可以尝试以下2种方式
方式#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;
}
}
但是你必须确保线程在调用 getData() 之前完成,例如,你可以使用 thread.join() 来做到这一点。
thread.start()
..//some jobs else
thread.join();
String data=thread.getData();
方式#3
在 run() 末尾使用一些静态回调方法
说
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);
}
}
关于java - run完成后调用线程对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26926588/