Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Q {
- int num;
- boolean valueSet = false;
- public synchronized void set(int num){
- // wait for get to retrieve before setting value again ..
- while(valueSet){
- try { wait(); } catch (Exception e){}
- }
- valueSet = true;
- this.num = num;
- System.out.println("set " +this.num);
- notify();
- }
- public synchronized void get(){
- // wait for set to put value before getting it
- while(valueSet == false){
- try { wait(); } catch (Exception e){}
- }
- System.out.println("get " +this.num);
- valueSet = false;
- notify();
- }
- }
- class Producer implements Runnable{
- Q q;
- public Producer(Q q){
- this.q = q;
- Thread t = new Thread(this, "Producer");
- t.start();
- }
- public void run(){
- int i=0;
- while(true){
- q.set(i++);
- try{
- Thread.sleep(100);
- }catch(Exception e){
- }
- }
- }
- }
- class Consumer implements Runnable{
- Q q;
- Consumer(Q q){
- this.q =q;
- Thread t = new Thread(this, "Consumer");
- t.start();
- }
- public void run(){
- while(true){
- q.get();
- try{
- Thread.sleep(1000);
- }catch(Exception e){
- }
- }
- }
- }
- public class Main{
- public static void main(String args[]) throws Exception{
- Q q = new Q();
- new Producer(q);
- new Consumer(q);
- /* here producer can produce faster than consumer can consume so
- we make producer wait till consumer sets flag to false ..
- and vice versa
- */
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement