此为Java语言程序设计的源代码
源代码在线查看: pctest.java
public class PCTest { //主程序
public static void main(String args[]){
Sharing s =new Sharing();
Producer p=new Producer(s,1);
Consumer c=new Consumer(s,1);
p.start();
c.start();
}
}
class Sharing{ //Producer和Consumer程序共享的资源对象
private int contents;
public int get(){
return contents;
}
public void put(int value){
contents=value;
}
}
class Producer extends Thread{ //Producer(生产者)程序
private Sharing shared;
private int number;
public Producer(Sharing s, int number){
shared=s;
this.number=number;
}
public void run(){
for(int i=0;i shared.put(i);
System.out.println("Producer"+this.number+"输出的数据为:"+i);
try{
sleep((int)(Math.random()*200));
}catch(InterruptedException e){}
}
}
}
class Consumer extends Thread { //Consumer(消费者)程序
private Sharing shared;
private int number;
public Consumer(Sharing s, int number){
shared=s;
this.number=number;
}
public void run(){
int value=0;
for(int i=0;i value=shared.get();
System.out.println("Consumer"+this.number+"得到的数据为:"+value);
}
}
}