Java Week9(B) Notepad

525 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
525
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
13
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Java Week9(B) Notepad

  1. 1. JAVA WEEK9(B) /* Week 9 : b) Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. */ class LabPro17 { int n; boolean vs = false; synchronized int get() { if(!vs) try{wait();} catch(InterruptedException e) { System.out.println("InterruptedException caught");} System.out.println("got:" + n); vs = false; notify(); return n; } synchronized int put(int n) { if(vs) try{wait();} catch(InterruptedException e) { System.out.println("InterruptedException caught");} this.n = n; vs = true; System.out.println("put:" + n); notify(); return n; } } class Producer implements Runnable { LabPro17 k; Producer(LabPro17 k) { this.k = k; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) {k.put(i++);} } } class Consumer implements Runnable { LabPro17 k; Consumer(LabPro17 k) { this.k = k; new Thread(this, "Consumer").start(); } public void run() { while(true) {k.get();} } } class PCFixed Page 1
  2. 2. JAVA WEEK9(B) { public static void main(String args[]) { LabPro17 k = new LabPro17(); new Producer(k); new Consumer(k); System.out.println("press control - c to stop. "); } } Page 2

×