pankaj lal pankaj lal - 4 months ago 20
Java Question

how to implement wait,notify with threadexecutor in java

how to implement wait,notify with threadexecutor in java,Suppose I have two objeccts of threadExecutor and I want to perform wait,notify on that objecct can we implement that.


Here is an Example of using wait notify with ThreadExecutor in Java :

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


        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;

        public void run() {
            synchronized (waitThread) {
                try {
                } catch (InterruptedException e) {

                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;

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

        public int getCount() {
            return count;




keyword is used for exclusive accessing.

To make a method synchronized, simply add the synchronized keyword to its declaration. Then no two invocations of synchronized methods on the same object can interleave with each other.

synchronized statements must specify the object that provides the intrinsic lock:


tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).


wakes up the first thread that called wait() on the same object.