您的位置:首页 > 编程语言 > Java开发

java多线程(生产消费)

2015-07-28 21:40 417 查看
/*
生产者,消费者。单生产,单消费。
*/
class Resource
{
private String name;
private int count=1;
private boolean flag = false;
public synchronized void  set(String name)
{

if (flag)
try{wait();}catch(InterruptedException e){}
this.name = name +count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者...."+this.name);
flag = true;
notify();

}
public synchronized void out()
{
if (!flag)
try{wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".........消费者.........."+this.name);
flag = false;
notify();

}
}
class Producer implements Runnable
{
private Resource r;
Producer(Resource r)
{
this.r=r;
}

public void run()
{
while (true)
{
r.set("馒头");
}

}
}
class Consumer implements Runnable
{
private Resource r;
Consumer(Resource r)
{
this.r=r;
}

public void run()
{
while (true)
{
r.out();
}

}

}
class  ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r = new Resource();

Producer pro = new Producer(r);
Consumer con = new Consumer(r);

Thread th1 = new Thread(con);
Thread th2 = new Thread(pro);

th1.start();
th2.start();

}
}




/*
生产者,消费者

多生产多消费问题。
其中继续使用单生产,单消费中的if判断语句的话,当有线程在wait后被notify后会直接执行生产任务(因为被wait后的线程在线程池中,notify后不会判断if)
所以此时就使用while判断。while解决了notify的线程不会往上执行判断语句。
但是如果当四个线程中三个都已经wait。最后一个线程执行notify(因为是随机的)被唤醒的是自己本方的线程,那么线程会在执行一次生产或者消费任务后继续wait。
这就造成死锁。解决办法就是每次都是唤醒notifyAll()。
*/
class Resource
{
private String name;
private int count=1;
private boolean flag = false;
public synchronized void set(String name)
{

while (flag)
try{wait();}catch(InterruptedException e){}
this.name = name +count;
count++;
System.out.println(Thread.currentThread().getName()+"...生产者...."+this.name);
flag = true;
notifyAll();

}
public synchronized void out()
{
while (!flag)
try{wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".........消费者.........."+this.name);
flag = false;
notifyAll();

}
}
class Producer implements Runnable
{
private Resource r;
Producer(Resource r)
{
this.r=r;
}

public void run()
{
while (true)
{
r.set("馒头");
}

}
}
class Consumer implements Runnable
{
private Resource r;
Consumer(Resource r)
{
this.r=r;
}

public void run()
{
while (true)
{
r.out();
}

}

}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r = new Resource();

Producer pro = new Producer(r);
Consumer con = new Consumer(r);

Thread th0 = new Thread(pro);
Thread th1 = new Thread(con);
Thread th2 = new Thread(pro);
Thread th3 = new Thread(con);
th0.start();
th1.start();
th2.start();
th3.start();

}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: