首页 > 代码库 > wait和notify实现的生产者消费者线程交互
wait和notify实现的生产者消费者线程交互
public class ProductTest {
public static void main(String args[])
{
Repertory repertory=new Repertory();
new Thread(new Producer(repertory)).start();
new Thread(new Consumer(repertory)).start();
}
}
class Repertory{
private int product=0;
public synchronized void addProduct(){
if(this.product>=5)
{
try{
this.wait();
}catch(Exception e)
{
e.printStackTrace();
}
}
else
{
product++;
System.out.println("生产者生成第"+product+"个产品");
this.notifyAll();
}
}
public synchronized void getProduct(){
if(this.product<=0)
{
try{
this.wait();
}catch(Exception e)
{
e.printStackTrace();
}
}else
{
System.out.println("消费者取走了第"+product+"个产品");
product--;
this.notifyAll();
}
}
}
class Producer implements Runnable{
private Repertory repertory;
public Producer(Repertory repertory){
this.repertory=repertory;
}
public void run(){
System.out.println("生产者开始生产产品");
while(true){
try{
Thread.sleep((int)(Math.random()*10)*100);
}catch(Exception e)
{
e.printStackTrace();
}
repertory.addProduct();
}
}
}
class Consumer implements Runnable{
private Repertory repertory;
public Consumer(Repertory repertory){
this.repertory=repertory;
}
public void run(){
System.out.println("消费者开始取走产品");
while(true)
{
try{
Thread.sleep((int)(Math.random()*10)*100);
}catch(Exception e)
{
e.printStackTrace();
}
repertory.getProduct();
}
}
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。