首页 > 代码库 > 线程同步之生产者与消费者

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

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 = http://www.mamicode.com/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 = http://www.mamicode.com/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();
}

}

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