- /*多线程 等待唤醒机制中的经典案例,生产者和消费者的问题*/
- class Resrour//共享资源
- {
- private String name;
- private int a=1;
- private boolean flag=false;
- public synchronized void set(String name)
- {
- while(flag)
- try{this.wait();}catch(InterruptedException e){}
- this.name= name + a;
- a++;
- System.out.println(Thread.currentThread().getName()+"..生产者生产了...."+name);
- [color=Red]我就是奇怪,这里为什么不输出编号[/color]
- flag=true;//存完值后更改标记变量
- notify();//唤醒读取线程
- }
- public synchronized void out()
- {
- while(!flag)
- try{this.wait();}catch(InterruptedException e){}
- System.out.println(Thread.currentThread().getName()+"..消费者消费了........"+name);
- flag=false;
- notify();
- }
- }
- //生产者线程任务
- class Producer implements Runnable
- {
- private Resrour r;
- Producer(Resrour r)
- {
-
- this.r=r;
- }
- public void run()
- {
- while(true)
- {
- r.set("烤鸭");
- }
- }
- }
- //消费者线程任务
- class Consumer implements Runnable
- {
- private Resrour r;
- Consumer(Resrour r)
- {
- this.r=r;
- }
- public void run()
- {
- while(true)
- {
- r.out();
- }
- }
- }
- class ThreadDemo3
- {
- public static void main(String[] args)
- {
- Resrour r=new Resrour();
- Producer pr=new Producer(r);
- Consumer co=new Consumer(r);
- Thread t0=new Thread(pr);
- Thread t1=new Thread(pr);
- Thread t2=new Thread(co);
- Thread t3=new Thread(co);
- t0.start();
- t1.start();
- t2.start();
- t3.start();
- }
- }
复制代码 |