码迷,mamicode.com
首页 > 编程语言 > 详细

线程同步之生产者与消费者

时间:2017-04-29 15:08:49      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:int   rac   cep   customer   cat   put   exception   ret   his   

public class Customer extends Thread{
private Queue q;
public Customer(Queue q){
this.q = q;
}

public void run(){
for(int i = 0; i < 10; i++){
int value = q.get();
}
}
}
public class Producer extends Thread{
private Queue q;
public Producer(Queue q){
this.q = q;
}

public void run(){
for(int i = 0; i < 10; i++){
q.put(i);

}
}
}
public class Queue {
int value;
boolean bFull = false;

synchronized public void put(int i){
if(bFull == false){
value = i;
bFull = true;
System.out.println("producer put " + i);
notify();
}
try{
wait();
}catch(Exception e){
e.printStackTrace();
}

}

synchronized public int get(){
if(bFull == false){
try{
wait();
}catch(Exception e){
e.printStackTrace();
}
}
bFull = false;
System.out.println("customer get " + value);
notify();
return value;
}
}
public class TestMain {

/**
* @param args
*/
public static void main(String[] args) {
Queue q = new Queue();
Producer p = new Producer(q);
Customer c = new Customer(q);
p.start();
c.start();
}

}

线程同步之生产者与消费者

标签:int   rac   cep   customer   cat   put   exception   ret   his   

原文地址:http://www.cnblogs.com/fengshaolingyun/p/6785150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!