pankaj lal pankaj lal - 11 days ago 5
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.

Answer

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

        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

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:

wait()

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

notify()

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