Java度线程——生产消费问题
该方法虽然可行,但是效率并非最好,JDK1.4版本已经无法解决效率问题,需要JDK1.5版本才能解决 1 class Resource 2 { 3 private String name; 4 private int count = 1; 5 boolean flag = false 6 public synchronized void set(String name)// 7 { 8 while(flag) 9 try{this.wait();}catch(InterruptedException e){}// t1 t0 10 11 this.name = name + count;烤鸭1 烤鸭2 烤鸭3 12 count++;2 3 4 13 System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);生产烤鸭1 生产烤鸭2 生产烤鸭3 14 flag = true15 notifyAll(); 16 } 17 18 void out() t3 19 20 while(!flag) 21 catch(InterruptedException e){} t2 t3 22 System.out.println(Thread.currentThread().getName()+"...消费者........"+消费烤鸭1 23 flag = 24 25 26 } 27 28 class Producer implements Runnable 29 30 Resource r; 31 Producer(Resource r) 32 33 this.r = r; 34 35 void run() 36 37 while() 38 { 39 r.set("烤鸭"); 40 } 41 42 43 44 class Consumer 45 46 47 Consumer(Resource r) 48 49 50 51 52 53 54 55 r.out(); 56 57 58 59 60 61 62 ProducerConsumerDemo 63 64 static main(String[] args) 65 66 Resource r = new Resource(); 67 Producer pro = Producer(r); 68 Consumer con = Consumer(r); 69 70 Thread t0 = Thread(pro); 71 Thread t1 = 72 Thread t2 = Thread(con); 73 Thread t3 = 74 t0.start(); 75 t1.start(); 76 t2.start(); 77 t3.start(); 78 79 80 }
该版本能够提高效率,因为我们不必唤醒所有对象,做多余的判断; 当然在这我们可以指定对象唤醒,在生产者生产完毕后,只需要唤醒消费者中的对象即可;反义,在消费者消费完毕后,我们只需指定唤醒生产者即可。 故我们的效率有所提升,因为不需要做多余的判断。 1 import java.util.concurrent.locks.* 2 3 4 5 6 7 8 9 创建一个锁对象。 10 Lock lock = ReentrantLock(); 11 12 通过已有的锁获取该锁上的监视器对象。 13 Condition con = lock.newCondition(); 14 15 通过已有的锁获取两组监视器,一组监视生产者,一组监视消费者。 16 Condition producer_con = lock.newCondition(); 17 Condition consumer_con = 18 19 20 public t0 t1 21 22 lock.lock(); 23 try 24 25 26 try{lock.wait();}catch(InterruptedException e){} 27 try{producer_con.await();} 28 29 30 count++; 31 System.out.println(Thread.currentThread().getName()+"...生产者5.0..."+ 32 flag = 33 notifyAll(); 34 con.signalAll(); 35 consumer_con.signal(); 36 37 finally 38 39 lock.unlock(); 40 41 42 43 44 t2 t3 45 46 47 48 49 50 try{this.wait();}catch(InterruptedException e){} 51 try{cousumer_con.await();} 52 System.out.println(Thread.currentThread().getName()+"...消费者.5.0......."+ 53 flag = 54 55 56 producer_con.signal(); 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 r.set("烤鸭" 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 ProducerConsumerDemo2 101 102 103 104 Resource r = 105 Producer pro = 106 Consumer con = 107 108 Thread t0 = 109 Thread t1 = 110 Thread t2 = 111 Thread t3 = 112 113 114 115 116 117 118 } ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |