Java等待池中的所有线程 [英] java wait all threads in pool

查看:196
本文介绍了Java等待池中的所有线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在按下暂停按钮并重新运行播放按钮时等待执行程序池中的所有线程?我尝试了CountDownLatch,但是我不知道我必须在执行程序声明之后还是在run()方法中放置它?我没有太多有关线程的信息.请有人告诉我我该怎么做.谢谢

Is there a way to wait all threads in executor pool when pause button pressed and rerun play button pressed? I tried CountDownLatch but I dont know I must put it after executor declaration or in run () method? I dont have much information about threads.please can someone tell me how I can do.Thanks

 public static CountDownLatch waiter;
public static ExecutorService pool;

public Action() throws InterruptedException{
    pool=Executors.newFixedThreadPool(2);
    waiter=new CountDownLatch(2); // to wait
    robot1=new Robot(0,560,"rbt1"); // starts random free position
    robot2=new Robot(0,560,"rbt2");
    if(Frame.pause==false){
       pool.submit(robot1);
       pool.submit(robot2);}
    if(Frame.pause==true){
        waiter.await();
    }


}

推荐答案

您的机器人工作人员需要一种共享的线程安全方式来检查工作人员是否应该暂停或玩耍.在工作程序的run()方法中,如果线程已暂停,请等待有关此锁定对象的通知.在循环或执行工作时,定期检查锁的状态,并在需要时暂停工作.

Your Robot worker needs a shared thread-safe way to check whether workers should be paused or playing. In the run() method of your worker, if the thread is paused, wait for notification on this lock object. While looping, or whatever it is the worker does, periodically check the state of the lock, and pause the worker if needed.

pauseIfNeeded() {
    synchronized(workerLock) {
        if (workerLock.isPaused()) {
            workerLock.wait();
        }
    }
}

您的暂停和播放"按钮应该在workerLock上获得同步锁,并设置被暂停的属性,然后在workerLock上调用notify().这将使工作人员根据需要暂停或继续.不管暂停/播放状态如何,执行器始终处于运行中"状态.

Your pause and play button should get a synchronized lock on the workerLock, and set the paused property, and call notify() on the workerLock. This will let the workers pause or continue as needed. The Executor is always "running", regardless of the paused/playing state.

编辑 您可以将上面的代码重构为自己的类,如下所示:

EDIT You can refactor the above code into its own class, as follows:

public class WorkerPauseManager {

    private boolean paused;

    public synchronized void pauseIfNeeded() throws InterruptedException {
        if (paused) wait();
    }

    public synchronized void pause() {
        this.paused = true;
    }

    public synchronized void start() {
        this.paused = false;
        notifyAll();
    }
}

创建WorkerPauseManager的单个实例.将此实例传递给所有的Robot工人,并保留参考作为挥杆暂停/播放动作的参考.您的辅助线程应调用pauseIfNeNeeded.

Create a single instance of WorkerPauseManager. Pass this instance to all your Robot workers, and keep a reference for the swing pause/play actions to reference. Your worker thread should call pauseIfNeeded.

这是使用WorkerPauseManager的SCCE:

Here's an SCCE using the WorkerPauseManager:

public class WorkerPauseManagerTest {
    public static void main(String[] args) {
        final WorkerPauseManager pauseManager = new WorkerPauseManager();
        new Worker("Worker 1", pauseManager).start();
        new Worker("Worker 2", pauseManager).start();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JToggleButton playPauseButton = new JToggleButton(new AbstractAction("Pause") {
                    public void actionPerformed(final ActionEvent e) {
                        JToggleButton source = (JToggleButton) e.getSource();
                        if (source.isSelected()) {
                            pauseManager.start();
                            source.setText("Pause");
                        } else {
                            pauseManager.pause();
                            source.setText("Play");
                        }
                    }
                });
                JOptionPane.showMessageDialog(null, playPauseButton, "WorkerPauseManager Demo", JOptionPane.PLAIN_MESSAGE);
                System.exit(0);
            }
        });

    }

    private static class Worker extends Thread {
        final String name;
        final WorkerPauseManager pauseManager;

        public Worker(final String name, final WorkerPauseManager pauseManager) {
            this.name = name;
            this.pauseManager = pauseManager;
        }

        @Override
        public void run() {
            while (!Thread.interrupted()) {
                try {
                    pauseManager.pauseIfNeeded();
                    System.out.println(name + " is running");
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

这篇关于Java等待池中的所有线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆