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

2ledvvac  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(408)

我正在使用服务。下面是代码

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方法中接收一个事件或一些东西。我该怎么做?

mccptt67

mccptt671#

当你 start 如果使用yourthread.start()创建一个线程,系统将启动一个新线程来执行 run 方法。您可以简单地打印如下内容: System.out.println("FINISHED " + this.getName()) 在比赛结束时 run 方法。
注:请确保你没有把上面的打印放在一些循环中,它应该是最后一个语句 run 方法.execute()方法与.start()几乎相同)

u1ehiz5o

u1ehiz5o2#

要了解任务状态,您需要将来的示例。现在有两点:
如果您只是想知道任务是否已完成,请使用 executorService.submit(worker) ,而不是 executorService.execute(worker) 方法。
如果您还想在任务完成后获得一些结果,请使用 Callable 接口而不是 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
h22fl7wq

h22fl7wq3#

你可以用 yourThread.join() .

相关问题