日期:2014-05-20  浏览次数:20748 次

多线程间通信问题,求解
本帖最后由 d5224161224 于 2013-01-23 14:38:51 编辑
需求:
生产者--消费者问题
生产一个商品,待消费完后再生产下一个
定义多个生产者和多个消费者
*/

package thread;

/*共享资源类,定义了两个方法setName()和print()*/
class Produce  
{
private String name;
private int count = 1;
private boolean flag = false;

public synchronized void setName(String name)//用于标识生产商品
{
while(flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}
this.name = name+"  -----  "+count++;
System.out.println(Thread.currentThread().getName()+"  -----  生产-----  "+this.name);
flag = true;
this.notifyAll();
}

public synchronized void print()  //用于标识消费商品
{
while (!flag)
{
try
{
wait();
}
catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()+"  ------ 消费  -----"+this.name);
flag = false;
this.notifyAll();
}
}
}


class Producer implements Runnable  //生产者类,实现Runnable接口
{
private Produce pro;

Producer(Produce pro)
{
this.pro = pro;
}

public void run()
{
while (true)
{
pro.setName("商品");
}
}
}


class Consumer implements Runnable  //消费者类,实现Runnable接口
{
private Produce pro;

Consumer(Produce pro)
{
this.pro = pro;
}

public void run()
{
while (true)
{
pro.print();
}
}
}


class ProducerConsumerDemo
{
public static void main(String[] args) 
{
Produce p = new Produce();

Producer per = new Producer(p);
Consumer c = new Consumer(p);

Thread t1 = new Thread(per);
Thread t2 = new Thread(per);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();

}
}

/*
疑问:
1.执行结果有问题,两个while循环没有执行。只有一行输出内容,然后程序就停住了、、
2.Porduce类中的函数setName()被synchronized所修饰,当线程t1进去后处于等待状态时,线程t2还能进去吗?
3.主线程执行完语句t4.start();之后干啥去了?
*/

------解决方案--------------------
1.你的问题  就是 print 方法里 大括号的位置扩错啦。。 你吧后面的NOTIFALL FLAG什么的都包括进去了
2.能 wait 释放锁
3.结束了 要等所有线程都结束 程序才能结束。 当然 你这个是循环 结束不了的