我正在使用 ExecutorService。以下是代码
public class A{
public static void main(String args[]){
ExecutorService executorService = Executors.newFixedThreadPool(5);
Runnable worker = new FileUploadThread("thread");
executorService.execute(worker);
}
}
public class FileuploadThread extends Thread{
//has a parametrized constuctor
@Override
public void run(){
for(int i=0; i<10000; i++){
syso("executing...");
}
}
}
当线程完成它的任务时,我想在 main 方法中接收一个事件或其他东西。我怎样才能做到这一点 ?
最佳答案
要了解任务状态 - 您需要 Future 实例。
现在有两点:
executorService.submit(worker)
, 而不是 executorService.execute(worker)
方法。 Callable
接口(interface)而不是 Runnable
.见下面的代码:public class A {
public static void main(String args[]){
ExecutorService executorService = Executors.newFixedThreadPool(5);
Callable<String> worker = new FileUploadThread("thread");
Future<String> workerTask = executorService.submit(worker);
try {
boolean isDone = workerTask.isDone();
System.out.println("Task is done: " + isDone);
//Wait untill task is executing
String status = workerTask.get();
System.out.println("Status: " + status);
isDone = workerTask.isDone();
System.out.println("Task is done: " + isDone);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executorService.shutdown();
}
}
class FileUploadThread implements Callable<String> {
//has a parametrized constuctor
public FileUploadThread(String thread) { }
@Override
public String call() throws Exception {
for(int i=0; i<5; i++){
System.out.println("executing..sleep for 1 sec...");
Thread.sleep(1000);
}
return "DONE";
}
}
输出:
Task is done: false
executing..sleep for 1 sec...
executing..sleep for 1 sec...
executing..sleep for 1 sec...
executing..sleep for 1 sec...
executing..sleep for 1 sec...
Status: DONE
Task is done: true
关于java - 我们如何知道线程已经完成了它的执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59891667/