java可以使用CountDownLatch来控制线程并发,使得一个或多个线程等待其他线程执行到某个操作后在执行。
如图示:
1.在CountDownLatch实例化的时候定义需要等待的线程count数。
2.通过CountDownLatch的await方法,当count数为0时唤醒。
3.每次执行完需要先执行的线程时使用countDown方法,使得count数减1,就成功实现其他线程都执行完才执行await后操作
package study.joker.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
public class test1 {
static Logger logger = LoggerFactory.getLogger(test1.class);
public static void main(String[] args) {
try {
final CountDownLatch latch = new CountDownLatch(3);
new Thread(() -> {
try {
logger.info("this is first Thread");
Thread.sleep(5000);
latch.countDown();
logger.info("this is first end ;latch.count={}", latch.getCount());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
logger.info("this is second Thread");
Thread.sleep(6000);
latch.countDown();
logger.info("this is second end;latch.count={}", latch.getCount());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
logger.info("this is third Thread begin");
Thread.sleep(7000);
latch.countDown();
logger.info("this is third Thread end;latch.count={}", latch.getCount());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
latch.await();//阻塞当前线程直到latch中数值为零才执行
// Thread.sleep(10);
logger.info("主线程执行!latch.count={}", latch.getCount());
while (true) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}