标签:
1 public class Wait implements Runnable{ 2 3 private String name; 4 private Object prev; 5 private Object slef; 6 7 public Wait(String name,Object prev,Object slef){ 8 this.name=name; 9 this.prev=prev; 10 this.slef=slef; 11 } 12 13 @Override 14 public void run() { 15 // TODO Auto-generated method stub 16 int count=10; 17 while(count>0){ 18 synchronized (prev) { 19 synchronized (slef) { 20 21 22 System.out.println(name); 23 count--; 24 25 slef.notify(); 26 27 } 28 try{ 29 prev.wait(); 30 } 31 catch (InterruptedException e){ 32 e.printStackTrace(); 33 } 34 } 35 } 36 } 37 public static void main(String[] args) throws Exception{ 38 Object a=new Object(); 39 Object b=new Object(); 40 Object c=new Object(); 41 42 Wait pa=new Wait("A",c,a); 43 Wait pb=new Wait("B",a,b); 44 Wait pc=new Wait("C",b,c); 45 46 new Thread(pa).start(); 47 Thread.sleep(100); 48 new Thread(pb).start(); 49 Thread.sleep(100); 50 new Thread(pc).start(); 51 Thread.sleep(100); 52 } 53 54 }
1 public class ThreadTest9 { 2 private static boolean flags=false; 3 4 public static void main(String[] args){ 5 class Goods{ 6 private String name; 7 private int num; 8 public synchronized void produce(String name){ 9 while(flags) 10 try{ 11 wait(); 12 }catch(InterruptedException e){ 13 e.printStackTrace(); 14 } 15 this.name=name+"编号:"+num++; 16 System.out.println(Thread.currentThread().getName()+"生产了。。。"+this.name); 17 flags=true; 18 notifyAll(); 19 } 20 21 public synchronized void consume(){ 22 while(!flags) 23 try{ 24 wait(); 25 }catch(InterruptedException e){ 26 e.printStackTrace(); 27 } 28 System.out.println(Thread.currentThread().getName()+"消费了*****"+this.name); 29 30 flags=false; 31 notifyAll(); 32 } 33 34 } 35 36 final Goods g=new Goods(); 37 new Thread(new Runnable(){ 38 39 @Override 40 public void run() { 41 // TODO Auto-generated method stub 42 while(true){ 43 g.produce("商品"); 44 } 45 } 46 47 },"生产者一号").start(); 48 new Thread(new Runnable(){ 49 50 @Override 51 public void run() { 52 // TODO Auto-generated method stub 53 while(true){ 54 g.produce("商品"); 55 } 56 } 57 58 },"生产者二号").start(); 59 new Thread(new Runnable(){ 60 61 @Override 62 public void run() { 63 // TODO Auto-generated method stub 64 while(true){ 65 g.consume(); 66 } 67 } 68 69 },"消费者一号").start(); 70 new Thread(new Runnable(){ 71 72 @Override 73 public void run() { 74 // TODO Auto-generated method stub 75 while(true){ 76 g.consume(); 77 } 78 } 79 80 },"消费者二号").start(); 81 } 82 83 }
标签:
原文地址:http://www.cnblogs.com/huangfuyoufeng/p/5757469.html