Advertisements
Home > Java > Java Program to show Thread Synchronization by user defined Get & Put methods – Q31

Java Program to show Thread Synchronization by user defined Get & Put methods – Q31


Q31: Java Program to create Q class having Get and Put methods and then create Producer and Consumer classes which accept Q object in their constructor. Put and get the numbers through a for loop in producer and consumer, use an array to put and get the numbers.

class Q{
	int n;

	synchronized int get(){
		System.out.println("Get: " + n);
		return n;
	}

	synchronized void put(int n){
		this. n = n;
		System.out.println("Put: " + n);
	}
}

class Producer implements Runnable{
	Q q;

	Producer(Q q){
		this.q = q;
		new Thread(this, "Producer").start();
	}

	public void run(){
		int i=0;
		while(true){
			q.put(i++);
		}
	}
}

class Consumer implements Runnable{
	Q q;

	Consumer(Q q){
		this.q = q;
		new Thread(this, "Consumer").start();
	}

	public void run(){
		while(true){
			q.get();
		}
	}
}

class PC{

	public static void main(String args[]){
		Q q = new Q();
		new Producer(q);
		new Consumer(q);
		
		System.out.println("Press Ctrl-C to STOP");
	}
}

… from College notes (BCA/MCA assignments):


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: