- Java并发编程:核心方法与框架
- 高洪岩
- 324字
- 2023-01-19 15:09:21
2.1.1 初步使用
在本节将实现一个当CountDownLatch的计数不为0时,线程呈阻塞状态的效果。通过本实验可以看到线程执行任务具有“组团”的特性了。
创建测试用的项目CountDownLatch_test1,类MyService.java代码如下:
package service; import java.util.concurrent.CountDownLatch; public class MyService { private CountDownLatch down = new CountDownLatch(1); public void testMethod() { try { System.out.println("A"); down.await(); System.out.println("B"); } catch (InterruptedException e) { e.printStackTrace(); } } public void downMethod() { System.out.println("X"); down.countDown(); } }
代码new CountDownLatch(1)的作用是创建1个计数的CountDownLatch类的对象,当线程执行down.await()代码时呈等待状态,程序不向下继续运行。程序执行down. countDown()代码时计数由1变成0,以前呈等待状态的线程继续向下运行。
线程类MyThread.java代码如下:
package extthread; import service.MyService; public class MyThread extends Thread { private MyService myService; public MyThread(MyService myService) { super(); this.myService = myService; } @Override public void run() { myService.testMethod(); } }
运行类Run.java代码如下:
package test.run; import service.MyService; import extthread.MyThread; public class Run { public static void main(String[] args) throws InterruptedException { MyService service = new MyService(); MyThread t = new MyThread(service); t.start(); Thread.sleep(2000); service.downMethod(); } }
程序运行结果如图2-2所示。
图2-2 运行结果
await()方法还有重载的写法await (long timeout, TimeUnit unit),此方法在2.1.5节有测试的代码。