网站开发答辩难点/整合营销方案案例
ondition可以实现多路Condition,notify只能通知随机的一个
如:ABC三个线程分别去处理一件事物,规则是A处理完通知B ,B处理完通知C,C通知A;如果使用notrfy无法做法这一点,所以我们可以使用Condition来new出来ABC三个Condition对象,来特定指明哪个对象await哪个对象single;
如:先放鸡蛋、拿鸡蛋、吃鸡蛋
public class EggServlet {private Lock lock = new ReentrantLock();Condition put = lock.newCondition();Condition get = lock.newCondition();Condition eatlock = lock.newCondition();int num = 0;int eat = 0;public void putEgg() {lock.lock();try {while (num!=0) {try {put.await();} catch (InterruptedException e) {e.printStackTrace();}}num++;System.out.println("放入了鸡蛋" + num);get.signal();} catch (Exception ep) {System.out.println(ep.toString());} finally {lock.unlock();}}public void getEgg() {lock.lock();while(num==0){try {get.await();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("拿到了鸡蛋" + num);num--;eat++;eatlock.signal();lock.unlock();}public void eatEgg() {lock.lock();while(eat==0){try {eatlock.await();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("吃鸡蛋" + num);System.out.println("=====================");eat--;put.signal();lock.unlock();}
}public class TestClient {public static void main(String[] args) {EggServlet egg = new EggServlet ();
<span style="white-space:pre"> </span>Thread t1 =new Thread(new PutThead(egg));
<span style="white-space:pre"> </span>Thread t2 = new Thread(new GetThead(egg));
<span style="white-space:pre"> </span>Thread t3 =new Thread(new EatThead(egg));
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>/*t1.start();
<span style="white-space:pre"> </span>t2.start();
<span style="white-space:pre"> </span>t3.start();*/
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>ExecutorService pool =Executors.newCachedThreadPool();
<span style="white-space:pre"> </span>pool.execute(t1);
<span style="white-space:pre"> </span>pool.execute(t2);
<span style="white-space:pre"> </span>pool.execute(t3);}}class PutThead implements Runnable {private EggServlet egg;public PutThead(EggServlet egg) {this.egg = egg;}@Overridepublic void run() {for (int i = 0; i < 10; i++) {egg.putEgg();}}
}class GetThead implements Runnable {private EggServlet egg;public GetThead(EggServlet egg) {this.egg = egg;}@Overridepublic void run() {for (int i = 0; i < 10; i++) {egg.getEgg();}}
}class EatThead implements Runnable {private EggServlet egg;public EatThead(EggServlet egg) {this.egg = egg;}@Overridepublic void run() {for (int i = 0; i < 10; i++) {egg.eatEgg();}}
}
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================
放入了鸡蛋1
拿到了鸡蛋1
吃鸡蛋0
=====================