学堂 学堂 学堂公众号手机端

生产者消费者

lewis 1年前 (2024-04-29) 阅读数 13 #技术


package pc;

public class Cusumer implements Runnable
{
SyncStack stack;

public Cusumer(SyncStack stack)
{

this.stack = stack;
}

public void run()
{
for(int i=0;i<20;i++)
{
char c=stack.pop();
}
try
{
Thread.sleep((int) (Math.random()*800));
}
catch (InterruptedException e)
{


e.printStackTrace();
}
}

}

package pc;
public class Produced implements Runnable
{
SyncStack stack;

public Produced(SyncStack stack)
{

this.stack = stack;
}

public void run()
{
for(int i=0;i<20;i++)
{
char c=(char)(Math.random()*26+'A');
stack.push(c);
}
try
{
Thread.sleep((int) (Math.random()*300));
}
catch (InterruptedException e)
{

e.printStackTrace();
}
}

}


package pc;
public class SyncStack
{
private int index=0;
private char [] data=new char[6];//存放数据的容器
//生产数据
public synchronized void push(char c)
{
while(index==data.length)//当容器data装满了
{
try
{
this.wait();//让当先线程出于等待状态
}
catch (InterruptedException e)
{

e.printStackTrace();
}
}
this.notify();//解除调用notify当前对象的锁定
data[index]=c;//继续生产数据
index++;
System.out.println("Produced:"+c);//打印生产的数据

}
//消费数据
public synchronized char pop()
{
while(index==0)//如果消费完了
{
try
{
this.wait();//让当先消费的线程出于等待状态
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();//唤醒消费的线程
index--;//继续消费
System.out.println("消费:"+data[index]);//打印消费的产品
return data[index];//返回消费的对象
}
}

package pc;

public class SyncTest
{

public static void main(String[] args)
{
SyncStack stack=new SyncStack();
Runnable p=new Produced(stack);
Runnable c=new Cusumer(stack);
Thread t1=new Thread(p);
Thread t2=new Thread(c);
t1.start();
t2.start();
}

}

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门