gpt4 book ai didi

java - run完成后调用线程对象方法

转载 作者:太空宇宙 更新时间:2023-11-04 06:24:53 26 4
gpt4 key购买 nike

我正在编写一个在单独线程上读取远程文件数据的类。

该类继承自thread,在run方法中读取一些远程文件数据。我将数据存储在一个字符串中。

我可以添加其他返回此数据字符串的方法吗?

我看到 isalive 在 run 方法返回后返回 false 值。

我需要使用事件机制吗?

请提出一些更好的解决方法。

最佳答案

方式#1

使用Callable相反,从 Future 获取此字符串.

在此处查看 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com