gpt4 book ai didi

java - 我们如何知道线程已经完成了它的执行?

转载 作者:行者123 更新时间:2023-12-03 13:16:49 26 4
gpt4 key购买 nike

我正在使用 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/

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