package 线程间的通信;
public class 生产者和消费者 {
public static void main(String[] args) {
Shangp sp = new Shangp();
Input i = new Input(sp);
Output o = new Output(sp);
Thread t1 = new Thread(i);
Thread t2 = new Thread(o);
t1.start();
t2.start();
}
}
class Input implements Runnable
{
Shangp s;
public Input(Shangp s)
{
this.s = s;
}
public void run()
{
while(true)
{
try
{
s.set("商品");
}
catch (Exception e) {
}
}
}
}
class Output implements Runnable
{
Shangp s ;
public Output(Shangp s)
{
this.s = s;
}
public void run()
{
while(true)
{
try
{
s.get();
}
catch (Exception e) {
}
}
}
}
class Shangp
{
String name ;
String xinxi;
int count = 0;
boolean flag = false;
public synchronized void set(String name)throws InterruptedException
{
while(!flag)//-----为true时开始生产
{
if(flag)wait();
this.name = name+count+++"-------";
System.out.println("生产"+count);
flag = true;
notify();
}
}
public synchronized void get() throws InterruptedException
{
while(flag)//-----为false时开始消费
{ if(flag)wait(); //为false就直接放弃执行权
System.out.println(".....消费"+count);
flag = false; //切换标识
notify(); //唤醒线程
}
//求救:为什么我这里只生产了1,就不在生产了啊。。。。
}
} |