1

I am using ExecutorService. Following is the code

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...");
        }
     }
}

I want to receive an event or something in the main method when the thread completes it task. How can i do that ?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Pri_stack
  • 179
  • 1
  • 12
  • Use `Callable` and return a value. Then `Future#get` can be used. – Prashant Jan 24 '20 at 06:57
  • Can you show me how ? or point out a link that i can refer ? – Pri_stack Jan 24 '20 at 06:59
  • https://www.geeksforgeeks.org/callable-future-java/ – Pri_stack Jan 24 '20 at 07:01
  • 2
    The declaration should be `FileuploadThread implements Runnable` instead of `FileuploadThread extends Thread`. It’s a mistake to allocate the resources of a `Thread` when you actually just need a `Runnable` (and a big mistake of the Java designers to let `Thread` implement `Runnable` leading to such mistakes). – Holger Jan 24 '20 at 09:34

3 Answers3

4

To know about the task status - You need Future instance. Now there are two points:

  1. If you are just interested to know whether the task has been completed or not, Use executorService.submit(worker) , instead of executorService.execute(worker) method.
  2. If you also want to get some result back after the task completion, Use Callable interface instead of Runnable. See below code:

    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";
      }
    }
    

Output:

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
pbajpai
  • 1,303
  • 1
  • 9
  • 24
  • statement workerTask.get(); does this method actually waits for the thread execution? if an exeception arise in the thread how it will be handled ? – Pri_stack Jan 24 '20 at 07:20
  • Yes. It does. It is explained in the javadoc. Exceptions are explained there too. – Stephen C Jan 24 '20 at 07:21
  • https://stackoverflow.com/questions/2248131/handling-exceptions-from-java-executorservice-tasks for those who require the link to handle exceptions – Pri_stack Jan 24 '20 at 07:32
  • 3
    @Pri_stack Just to note, you don't _have_ to switch to `Callable` in order to get a `Future`, assuming you don't need a result. There's the [`ExecutorService#submit(Runnable)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/concurrent/ExecutorService.html#submit(java.lang.Runnable)) overload. – Slaw Jan 24 '20 at 08:05
0

When you start a thread with yourThread.start(), the system starts a new thread doing what is inside the run method. You can simply print something like this : System.out.println("FINISHED " + this.getName()) at the end of the run method.

PS : please make sure you don't place the print above in some loops, it should be the last statement in the run method. ( The .execute() method is almost the same thing with .start() )

user1234SI.
  • 1,812
  • 1
  • 8
  • 22
0

You could use yourThread.join().

fastcodejava
  • 39,895
  • 28
  • 133
  • 186