Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i know threads jobs are done?

In class B how can i know jobs of threads are finished? In after properties some worker are running. In class B, I need to know if worker are done?

public class A implements InitializingBean{
     public void method1(){
        ...
    }    
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.print("test after properties set");      
        // send threads to executorService
        ExecutorService executorService = Executors
                .newFixedThreadPool(4);
        for (int i = 0; i < 4; i++) {
            Worker worker = new Worker();       
            executorService.submit(worker);
        }
    }
}
public class Worker implements Callable<Void>{
    @Override       
    public void call(){
     ...
   }
}
public class B{
   public void methodB(){
      A a = new A();
     a.method1();
     ///Here How can i know the job of the workers are finished?
   }
}
like image 555
Fariba Avatar asked Jul 31 '15 19:07

Fariba


People also ask

How do you know when a thread is finished?

In JavaSW, a thread is considered to be alive when its start() method has been called. After the run() method finishes, the thread is considered to not be alive anymore. We can determine if a thread is currently alive or not by calling a Thread instance's isAlive() method. The getState() method can also be useful.

What happens when a thread finishes?

Thread Termination After finish their work, threads terminate. In the quicksort example, after both array subsegments are sorted, the threads created for sorting them terminate. In fact, the thread that creates these two child threads terminates too, because its assigned task completes.

How do I know if a python thread is running?

is_alive() method is an inbuilt method of the Thread class of the threading module in Python. It uses a Thread object, and checks whether that thread is alive or not, ie, it is still running or not. This method returns True before the run() starts until just after the run() method is executed.


3 Answers

Use a listener/callback pattern to have the thread report completion to a listener. This simple example should show the process:

public interface ThreadCompleteListener {
    void workComplete();
}

public class NotifyingThread extends Thread {
    private Set<ThreadCompleteListener> listeners;
    // setter method(s) for adding/removing listeners to go here

    @Override
    public void run() {
        // do stuff
        notifyListeners();
    }

    private void notifyListeners() {
        for (ThreadCompleteListener listener : listeners) {
            listener.workComplete(); // notify the listening class
        }
    }
}

in your listening class:

NotifyingThread t = new NotifyingThread();
t.addListener(new ThreadCompleteListener() {
    void workComplete() {
        // do something
    }
});

t.start();
like image 200
Ryan J Avatar answered Oct 01 '22 16:10

Ryan J


You could use a Future implementation for your thread. It provides a Future#isDone()

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html#isDone()

like image 26
Ezequiel Avatar answered Oct 01 '22 16:10

Ezequiel


In general, it is usually more useful to be notified via a callback when jobs complete. However, since others have posted answers which follow that model, I'll instead post a solution that simply allows you to poll and ask whether the jobs are finished, in case this is what fits the needs of your application better.

public static interface InitializingBean{
    public void afterPropertiesSet() throws Exception;
}

public static class A implements InitializingBean{

    private List<Future<Void>> submittedJobs = Collections.synchronizedList(new ArrayList<Future<Void>>());  

    public void method1(){
        //do stuff
    }    
    @Override
    public void afterPropertiesSet() throws Exception {
                    System.out.print("test after properties set");      
        // send threads to executorService
        ExecutorService executorService = Executors
                .newFixedThreadPool(4);
        synchronized (submittedJobs) {              
            for (int i = 0; i < 4; i++) {
                Worker worker = new Worker();       
                submittedJobs.add(executorService.submit(worker));
            }
        }
    }

    /**
     * Allows you to poll whether all jobs are finished or not.
     * @return
     */
    public boolean areAllJobsFinished(){
        synchronized (submittedJobs) {              
            for(Future<Void> task : submittedJobs){
                if(!task.isDone()){
                    return false;
                }
            }

            return true;
        }
    }
}
public static class Worker implements Callable<Void>{
    @Override       
    public Void call(){
     //do worker job

     return null; //to satisfy compiler that we're returning something.
   }
}
public static class B{
   public void methodB(){
      A a = new A();
     a.method1();

     if(a.areAllJobsFinished()){
         System.out.println("Congrats, everything is done!");
     } else {
         System.out.println("There's still some work being done :-(");
     }
   }
}
like image 25
augray Avatar answered Oct 01 '22 15:10

augray