How to communicate between threads in java




Asked on March 23, 2014
Hi All,

Please let me know what are all the possible ways to communicate between threads in java.





Replied on March 23, 2014
Hi Jeet, I had googled and and found this..hope this will help you..

public class EvenRunnable implements Runnable {
    private int number = 2;
    private Object shared = null;
    public EvenRunnable(Object object) {
        shared = object;
    }
    public void run() {
        while (number < 50) {
            synchronized (shared) {
                System.out.println("Even number =  " + number);
                number = number + 2;
                try {
                    Thread.sleep(500); //only to view sequence of execution
                    shared.notify();
                    shared.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

-----------------------------------
public class OddRunnable implements Runnable {
    int oddNumber = 1;
    private Object shared = null;
    public OddRunnable(Object object) {
        shared = object;
    }
    public void run() {
        while (oddNumber < 50) {
            synchronized (shared) {
                System.out.println("Odd number = " + oddNumber);
                oddNumber = oddNumber + 2;
                try {
                    Thread.sleep(500); // only to view the sequence of execution
                    shared.notify();
                    shared.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();  
                }
            }
        }
    }
}

--------------------------------
Now let us see the main  class.

public class Main {
    public Main(){
           }
    public static void main(String[] args) {
        Object shared = new Object();
        EvenRunnable evenRunnable = new EvenRunnable(shared);
        OddRunnable oddRunnable = new OddRunnable(shared);
        Thread evenThread = new Thread(evenRunnable, "evenThread");
        Thread oddThread = new Thread(oddRunnable, "oddThread");
        oddThread.start();
        evenThread.start();
    }
}





Replied on March 23, 2014
I just remembered one more way to communicate between threads




Replied on March 23, 2014
Thanks a lot to all of you for providing such a nice info.

Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us