Thread intercommunication

package threaddemo;
class SharedObject {
	int contents = 0;
	boolean available = false;
	synchronized int get() {
		if (available == false)
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("InterruptedException caught");
			}
		System.out.println("consume: " + contents);
		available = false;
		notifyAll();
		return contents;
	}
	synchronized void put(int num) {
		if (available == true)
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("InterruptedException caught");
			}
		contents = num;
		System.out.println("Produce: " + contents);
		available = true;
				notifyAll();
	}
}
class Producer extends Thread {
	SharedObject s;
	Producer(SharedObject s) {
		this.s = s;
		this.start();
	}
	public void run() {
		int i = 0;
		for (; i < 10; i++)
			s.put(i);
	}
}
class Consumer extends Thread {
	SharedObject s;
	Consumer(SharedObject s) {
		this.s = s;
		this.start();
	}
	public void run() {
		for (int i = 0; i < 10; i++)
			s.get();
	}
}
public class InterThreadCom {
	public static void main(String[] args) {
		SharedObject s = new SharedObject();
		new Producer(s);
		new Consumer(s);
	}
}

Download

Thread Source Code

Thread by extending Thread class
Thread by implementing Runnable interface
Multithread by implementing Runnable interface
Thread Intercommunication
Thread Join Example
Thread Join Example
Main Thread information
Multithreaded Example
Thread Priority
Thread Priority
Thread yield example


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code