日期:2014-05-20 浏览次数:20792 次
class Producer extends Thread{
private PCQueue pcqueue;
private int number;
public Producer(PCQueue pcqueue,int number){
this.pcqueue=pcqueue;
this.number=number;
}
public void run(){
for(int i=0;i<10;i++){
pcqueue.put(i);
System.out.println("Producer # "+this.number+" put: "+i);
try{
sleep((int)Math.random()*100);
}catch(Exception e){}
}
}
}
class PCQueue{
private int seq;
private boolean available=false; //缓冲区
public synchronized int get(){
while(available==false){ //缓冲区空的
try{
System.out.println("缓冲区是空的,没有商品可以拿出来"+available);
// System.out.println(available);
wait();
}catch(InterruptedException e){}
}
available=false;
notifyAll();
return seq;
}
public synchronized void put(int value){
while(available==true){ //缓冲区满的
try{
System.out.println("缓冲区满的,不可以再生产商品"+available);
wait();
}catch(InterruptedException e){}
}
available=true;
seq=value;
notifyAll();
}
}
class Consumer extends Thread{
private PCQueue pcqueue;
private int number;
public Consumer(PCQueue pcqueue,int number){
this.pcqueue=pcqueue;
this.number=number;
}
public void run(){
int value=0;
for(int i=0;i<10;i++){
value=pcqueue.get();
System.out.println("Consumer #"+this.number+" got"+value);
}
}
}
public class ProducerConsumer {
public static void main(String args[]){
PCQueue pcqueue = new PCQueue();
Producer p1=new Producer(pcqueue,1);
Consumer c1=new Consumer(pcqueue,1);
p1.start();
c1.start();
}
}
class Producer extends Thread {
private PCQueue pcqueue;
private int number;
public Producer(PCQueue pcqueue, int number) {
this.pcqueue = pcqueue;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
pcqueue.put(i);
try {
sleep((int) Math.random() * 100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class PCQueue {
private int seq;
private boolean available = false; // 缓冲区
public synchronized int get() {
while (available == false) { // 缓冲区空的
try {
System.out.println("缓冲区是空的,没有商品可以拿出来" + available);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumer got: " + this.seq);
available = false;
notifyAll();
return seq;
}
public synchronized void put(int value) {
while (available == true) { // 缓冲区满的
try {
System.out.println("缓冲区满的,不可以再生产商品" + available);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Producer # put: " + value);
available = true;
seq = value;
notifyAll();
}
}
class Consumer extends Thread {
private PCQueue pcqueue;
private int number;
public Consumer(PCQueue pcqueue, int number) {
this.pcqueue = pcqueue;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = pcqueue.get();
}
}
}
public class ProducerConsumer {
public static void main(String args[]) {
PCQueue pcqueue = new PCQueue();
Producer p1 = new Producer(pcqueue, 1);