我们如何知道线程已完成执行?

How do we come to know that the thread has finished its execution?

我正在使用 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 方法中接收事件或其他内容。我该怎么做?

当你start一个线程yourThread.start()时,系统会启动一个新线程来执行run方法中的操作.您可以简单地打印如下内容:System.out.println("FINISHED " + this.getName())run 方法的末尾。

PS :请​​确保不要将上面的打印放在某些循环中,它应该是 run 方法中的最后一条语句. ( .execute() 方法 几乎 与 .start() 相同)

你可以使用 yourThread.join().

要了解任务状态 - 您需要 Future 实例。 现在有两点:

  1. 如果您只是想知道任务是否已完成,请使用 executorService.submit(worker) 而不是 executorService.execute(worker) 方法。
  2. 如果您还想在任务完成后返回一些结果,请使用 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