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):
Categories: Java
Java OO Programs, Runnable Interface, Thread Synchronization
Comments (0)
Trackbacks (0)
Leave a comment
Trackback




