Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Queue{
- int item=0;
- boolean busy=false;
- synchronized int get(){
- if(!busy){
- try{
- wait();
- } catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- System.out.println("GET: "+item);
- busy=false;
- notify();
- return item;
- }
- synchronized void put(int item){
- if(busy){
- try{
- wait();
- } catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- System.out.println("PUT: "+item);
- this.item=item;
- busy=true;
- notify();
- }
- }
- class Producer extends Thread{
- int i=0;
- Queue q;
- Producer(Queue q){
- this.q=q;
- setName("Producer");
- start();
- }
- public void run(){
- try{
- while(i<=10) q.put(i++);
- Thread.sleep(500);
- } catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- }
- class Consumer extends Thread{
- Queue q;
- Consumer(Queue q){
- this.q=q;
- setName("Consumer");
- start();
- }
- public void run(){
- int i=0;
- while(true){
- try{
- q.get();
- Thread.sleep(500);
- } catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- }
- }
- class Main{
- public static void main(String args[]){
- Queue q=new Queue();
- new Producer(q);
- new Consumer(q);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement