- /*
- 生产者消费者的线程同步问题
- */
- class Res
- {
- private String name;
- private int count=1;
- private boolean flag=false;
- public synchronized void set(String name)
- {
- if(flag)
- try{wait();}catch(Exception e){}
- this.name=name+"----"+count++;
- System.out.println(Thread.currentThread().getName()+"-------生产者--"+this.name);
- flag=true;
- notify();
- }
- public synchronized void out()
- {
- if(!flag)
- try{wait();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"--------消费者------"+this.name);
- flag=false;
- notify();
- }
- }
- class Pro implements Runnable
- {
- private Res r;
- Pro(Res r)
- {
- this.r=r;
- }
- public void run()
- {
- while(true)
- {
- r.set("冰激凌");
- }
- }
-
- }
- class Con implements Runnable
- {
- private Res r;
- Con(Res r)
- {
- this.r=r;
- }
- public void run()
- {
- while (true)
- {
- r.out();
- }
-
- }
- }
- class ProConDemo
- {
- public static void main(String[] args)
- {
- Res r=new Res();
- new Thread(new Pro(r)).start();
- new Thread(new Con(r)).start();
- }
- }
复制代码
|
|