一,Condition
一个场景,两个线程数数,同时启动两个线程,线程A数1、2、3,然后线程B数4、5、6,最后线程A数7、8、9,程序结束,这涉及到线程之间的通信。
public class ConditionTest { static class NumberWrapper { public int value = 1; } public static void main(String[] args) { //初始化可重入锁 final Lock lock = new ReentrantLock(); //第一个条件当屏幕上输出到3 final Condition reachThreeCondition = lock.newCondition(); //第二个条件当屏幕上输出到6 final Condition reachSixCondition = lock.newCondition(); //NumberWrapper只是为了封装一个数字,一边可以将数字对象共享,并可以设置为final //注意这里不要用Integer, Integer 是不可变对象 final NumberWrapper num = new NumberWrapper(); //初始化A线程 Thread threadA = new Thread(new Runnable() { @Override public void run() { //需要先获得锁 lock.lock(); System.out.println("ThreadA获得lock"); try { System.out.println("threadA start write"); //A线程先输出前3个数 while (num.value <= 3) { System.out.println(num.value); num.value++; } //输出到3时要signal,告诉B线程可以开始了 reachThreeCondition.signal(); } finally { lock.unlock(); System.out.println("ThreadA释放lock"); } lock.lock(); try { //等待输出6的条件 System.out.println("ThreadA获得lock"); reachSixCondition.await(); System.out.println("threadA start write"); //输出剩余数字 while (num.value <= 9) { System.out.println(num.value); num.value++; } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); System.out.println("ThreadA释放lock"); } } }); Thread threadB = new Thread(new Runnable() { @Override public void run() { try { lock.lock(); System.out.println("ThreadB获得lock"); Thread.sleep(5000);//是await方法释放了锁 while (num.value <= 3) { //等待3输出完毕的信号 reachThreeCondition.await(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); System.out.println("ThreadB释放lock"); } try { lock.lock(); System.out.println("ThreadB获得lock"); //已经收到信号,开始输出4,5,6 System.out.println("threadB start write"); while (num.value <= 6) { System.out.println(num.value); num.value++; } //4,5,6输出完毕,告诉A线程6输出完了 reachSixCondition.signal(); } finally { lock.unlock(); System.out.println("ThreadB释放lock"); } } }); //启动两个线程 threadB.start(); threadA.start(); } }
创建方式:通过Lock创建,Lock.newCondition();
常用方法:
await():阻塞,直到相同的Condition调用了signal方法。
signal():通知。
总结:Condition必须与Lock一起使用(wait()、notify()必须与synchronized一起使用,否则运行会报错java.lang.IllegalMonitorStateException),相比于wait与notify更加的灵活,可以设置各种情形,如上例中的到达3和到达6两个条件。
二,CountDownLatch
直接上代码:
public class CountDownLatchTest { public static void main(String[] args) { final CountDownLatch c = new CountDownLatch(3);//总数3 Thread t1 = new Thread(new Runnable(){ @Override public void run() { try { System.out.println("开始等"); c.await();//阻塞,等待countDown,当countDown到0就执行后面的完事了 System.out.println("完事"); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable(){ @Override public void run() { for(int i=3;i>0;i--){ c.countDown();//减1 } } }); t1.start(); t2.start(); }}
创建方式:直接创建,new CountDownLatch(int num);
常用方法:
await():阻塞,直到countDown方法被执行了num次。
countDown():减
总结:适用于一个线程等待其他线程的情景。
三,CyclicBarrier
通过代码思考一下与CountDownLatch的区别。
public class MainMission { private CyclicBarrier barrier; private final static int threadCounts = 5; public void runMission() { ExecutorService exec=Executors.newFixedThreadPool(threadCounts); //new 的时候要传入数字,我发现,这个类似semaphore,如果位置不足,线程会抢位置。数字要是threadCounts+1为主线程留一个位子,但实际测试中发现,只要等于threadCount就可以 barrier=new CyclicBarrier(threadCounts+1); for(int i=0;i<5;i++){ exec.execute(new Mission(barrier)); } try { barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("所有任务都执行完了"); exec.shutdown();//如果不关闭,程序一直处于运行状态 } public static void main(String[] args) { MainMission m = new MainMission(); m.runMission(); } } class Mission implements Runnable{ private CyclicBarrier barrier; public Mission(CyclicBarrier barrier){ this.barrier = barrier; } @Override public void run() { System.out.println(Thread.currentThread().getName()+"开始执行任务"); try { int sleepSecond = new Random().nextInt(10)*1000; System.out.println(Thread.currentThread().getName()+"要执行"+sleepSecond+"秒任务"); Thread.sleep(sleepSecond); } catch (InterruptedException e) { e.printStackTrace(); } try { barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"执行完毕"); } }
创建方式:直接创建,new CyclicBarrier(int num);
常用方法:
await():阻塞,直到阻塞的线程数量达到num个。
总结:想想一下百米跑,所有运动员都就位之后才会发令起跑,线程调用await意味着说,我准备好了。
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #0080e1 }
span.s1 { text-decoration: underline }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }
原文地址:https://www.cnblogs.com/coolgame/p/8746750.html