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

January 16, 2009 Leave a comment Go to comments

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


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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: