黑马程序员技术交流社区
标题:
生产与消费,多线程的实际使用
[打印本页]
作者:
iceknc
时间:
2015-9-20 22:15
标题:
生产与消费,多线程的实际使用
class Goods
{
private String name;
private int count = 0;
private boolean flag = false;
public synchronized void set(String name)
{
while(flag)//线程被唤醒的时候都进一次判断,如用if只能判断一次
try{wait();}catch(Exception e){} //此处只做简单处理,会抛出interrupt异常,暂时不会处理
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName() + "....生产者" + this.name);
flag = true;
notifyAll();//唤醒线程池里的线程
}
public synchronized void out()
{
while(!flag)
try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName() + "-------------消费者" + this.name);
flag = false;
notifyAll();
}
}
class Producer implements Runnable
{
private Goods g;
public Producer(Goods g)
{
this.g = g;
}
public void run()
{
while(true)
{
g.set("##商品##");
}
}
}
class Consumer implements Runnable
{
private Goods g;
public Consumer(Goods g)
{
this.g = g;
}
public void run()
{
while(true)
{
g.out();
}
}
}
复制代码
class Test
{
public static void main(String[] args)
{
Goods g = new Goods();
Producer pro = new Producer(g);
Consumer consumer = new Consumer(g);
//4个生产,2个消费
new Thread(pro).start();
new Thread(pro).start();
new Thread(pro).start();
new Thread(pro).start();
new Thread(consumer).start();
new Thread(consumer).start();
}
}
复制代码
1.关于wait()使用while循环,因为线程在这被唤醒之后,需要第一时间判断所操作资源的状态,所以只能使用while来强制线程被唤醒就进判断
2.关于notifyAll(),因为正常循环中是生产的完成动作后唤醒消费的线程,但是现有机制下无法唤醒指定的线程,所以运行中容易造成唤醒的是同一边的线程,然后全部线程进入wait()状态,因此,唤醒全部线程是比较行之有效的方法。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2