- class Res
- {
- private String name;
- private int count=1;
- private boolean flag;
- public synchronized void set(String name)
- {
- while (flag)
- try{this.wait();}catch(Exception e){}
- this.name=name+"---"+count++;
- System.out.println(Thread.currentThread().getName()+"生产者。。。。。。。"+this.name);
- flag=true;
- this.notifyAll();
-
- }
- public synchronized void out()
- {
- while (!flag)
- try{this.wait();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"消费者"+this.name);
- flag=false;
- this.notifyAll();
- }
- }
- 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 test
- {
- public static void main(String[] args)
- {
- Res r=new Res();
- Pro p=new Pro(r);
- Con c=new Con(r);
- Thread t1=new Thread(p);
- Thread t2=new Thread(p);
- Thread t3=new Thread(c);
- Thread t4=new Thread(c);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
- 这是什么问题,运行后电脑会嘟嘟几声,然后出现这样的乱码,这代码没什么问题吧
复制代码
|
|