如何实现wait,在java中用threadexecutor通知

时间:2016-11-27 12:33:01

标签: java multithreading

如何实现wait,在java中使用threadexecutor进行通知,假设我有两个threadExecutor的目标,我想执行wait,通知该目标可以实现。

1 个答案:

答案 0 :(得分:0)

以下是在Java中使用等待通知和ThreadExecutor的示例:

public class ExecutorServiceTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        ThreadB threadB = new ThreadB();
        ThreadA threadA = new ThreadA(threadB);

        executor.execute(threadA);
        executor.execute(threadB);

        executor.shutdown();
        while (!executor.isTerminated());
        System.out.println("Finished all threads");

    }

    static class ThreadA extends Thread {

        private final ThreadB waitThread;

        public ThreadA(ThreadB waitThread) {
            this.waitThread = waitThread;
        }

        @Override
        public void run() {
            synchronized (waitThread) {
                try {
                    waitThread.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("B Count Total : " + waitThread.getCount());

                for (int i = waitThread.getCount(); i < 200; i++) {
                    System.out.println("A Counting " + i);
                }
            }
        }
    }

    static class ThreadB extends Thread {

        private int count = 0;

        @Override
        public void run() {
            synchronized (this) {
                while (count < 100) {
                    System.out.println("B Counting " + count);
                    count++;
                }
                notify();
            }
        }

        public int getCount() {
            return count;
        }

    }

}

同步

  

关键字用于独占访问。

     

要使方法同步,只需将synchronized关键字添加到其声明中即可。然后,对同一对象的两个同步方法的调用不能相互交错。

     

synchronized语句必须指定提供内部锁的对象:

wait()

  

告诉调用线程放弃监视器并进入休眠状态,直到某个其他线程进入同一监视器并调用notify()。

notify()

  

唤醒在同一个对象上调用wait()的第一个线程。