Tuesday, 27 May 2014

Usage of wait,notify and notifyAll.

Following code demonstrates the the wait,notifyAll working.I have created one linkedlist object.
  Working of code is as below:
  1.First thread is created and set priority to 5 and called wait method.It will be in waiting state until it receives notify .
  2.Created second thread and set priority to 6 and called wait method.It will be in waiting state until it receives notify .
  3.Create third thread and added one element to list and called notifyAll method. In this ,notifyAll method will notify to second thread because priority is higher than first thread.It executes second thread then first thread. Always wait,notify,notifyAll methods get called from synchronized blocks or methods.
=======================code starts==================================
public static void main(String[] args) {
        // TODO Auto-generated method stub
        final LinkedList<String> ll=new LinkedList<String>();
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                synchronized (ll) {
                    try {
                        Thread.currentThread().setPriority(5);
                        ll.wait();
                        System.out.println("first thread="+ll);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }).start();


        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                synchronized (ll) {
                    try {
                        Thread.currentThread().setPriority(6);
                        ll.wait();
                        System.out.println("second thread="+ll);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                synchronized (ll) {
                    ll.add("abc");
                    ll.notifyAll();
                    System.out.println("Third thread="+ll);
                }
            }
        }).start();
    }

}

=============code ends========================================================

1 comment:

  1. can give sample example for notify and notifyall methods

    ReplyDelete