简体   繁体   English

我如何知道线程作业已完成?

[英]How can i know threads jobs are done?

In class B how can i know jobs of threads are finished? 在B类中,我如何知道线程作业已完成? In after properties some worker are running. 在after属性中,一些工作程序正在运行。 In class B, I need to know if worker are done? 在班B中,我需要知道工作人员是否完成了吗?

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?
   }
}

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();

You could use a Future implementation for your thread. 您可以为线程使用Future实现。 It provides a Future#isDone() 它提供一个Future#isDone()

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

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

If you'd like to wait in that thread that starts the ExecutorService, you can actually use the awaitTermination method. 如果您想在启动ExecutorService的线程中等待,则可以实际使用awaitTermination方法。

At the end of you afterPropertiesSet method, you should add: 在afterPropertiesSet方法的最后,您应该添加:

executorService.shutdown();

After this you then add: 在此之后,您可以添加:

executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS)

This causes the thread to wait for all the executorService's tasks to be done and then continues. 这将导致线程等待executorService的所有任务完成,然后继续。 So place any code you want to execute after the call to awaitTermination. 因此,在调用awaitTermination之后放置要执行的任何代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我怎样才能知道ThreadPoolExecutor中的线程已经完成? - How can I tell that threads in ThreadPoolExecutor are done? 我怎么知道共享意图呢? - how can I know sharing intent done? 如何确保所有产生的线程都已完成,以便继续处理? - How can I make sure that all the spawned threads are done so that processing can continue? 在Java中:如何在不等待使用ExecutorService完成作业的情况下终止所有线程的执行? - in java: how can i terminate execution of all threads without waiting for them to finish their jobs using ExecutorService? 在使用Swing的Java中,我怎么知道用invokeLater启动的所有线程何时完成? - In Java using Swing, how can I know when all threads launched with invokeLater have finished? 我如何知道当前JVM允许的最大可运行线程数? - How can I know the maximum number of runnable threads allowed on the current JVM? 我如何知道是否在面板中的自定义组件上单击了鼠标? - How do i know if a mouse click is done on a custom component in a panel? 我有两个线程如何知道它们是否同时运行? - I have two threads how do I know if they are running concurrently? 如何禁用Quartz JDBCJobStore中的作业? - How can I disable jobs in the Quartz JDBCJobStore? 我如何安排自动打印作业? - How can i schedule automatically print jobs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM