標籤:als try static not class rcu zed dem this
生產者消費者
1 class Resource 2 { 3 private String name; 4 private int count = 1; 5 private boolean flag = false; 6 7 public synchronized void set(String name) 8 { 9 while(flag)10 try{this.wait();}catch(Exception e){}11 this.name = name+"--"+count++;12 System.out.println(Thread.currentThread().getName()+"...生產者..."+this.name);13 flag = true;14 this.notifyAll();15 }16 17 public synchronized void out()18 {19 while(!flag)20 try{this.wait();}catch(Exception e){}21 System.out.println(Thread.currentThread().getName()+"...消費者..."+this.name);22 flag = false;23 this.notifyAll();24 }25 }26 27 class Producer implements Runnable28 {29 private Resource res;30 31 Producer(Resource res)32 {33 this.res = res;34 }35 36 public void run()37 {38 while(true)39 {40 res.set("+TT+");41 }42 }43 }44 45 class Customer implements Runnable46 {47 private Resource res;48 49 Customer(Resource res)50 {51 this.res = res;52 }53 54 public void run()55 {56 while(true)57 {58 res.out();59 }60 }61 }62 class ProducerCustomerDemo63 {64 public static void main(String[] args)65 {66 Resource r = new Resource();67 68 Producer pro = new Producer(r);69 Customer con = new Customer(r);70 71 Thread t1 = new Thread(pro);72 Thread t2 = new Thread(con);73 74 t1.start();75 t2.start();76 }77 }View Code
JAVA中的多線程(六)