当我们在开发多线程应用程序时,经常需要在等待某一些任务完成后再继续执行下去。Java中提供了多种同步工具类,包括CountDownLatch。
CountDownLatch是一个同步工具类,用于等待一个或多个线程执行完毕后再执行另一个或多个线程。CountDownLatch通过计数器来实现,计数器初始化为一个整数,当计数器为0时,另一个线程可以执行。
以下是使用CountDownLatch的示例:
示例1:一组线程等待某个线程完成后再继续执行
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread1 is running");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1 is done");
countDownLatch.countDown();
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread2 is waiting for Thread1 to finish");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread2 is running");
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}
在这个例子中,我们使用了CountDownLatch来使线程2等待线程1结束后再执行。当线程1开始运行时,它打印“Thread1 is running”,睡眠2秒钟后再打印“Thread1 is done”,然后减少CountDownLatch的计数器。线程2等待CountDownLatch的计数器为0,一旦它变为0,线程2就开始运行,并打印“Thread2 is running”。
示例2:一组线程等待所有线程完成后再继续执行
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(3);
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread1 is running");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1 is done");
countDownLatch.countDown();
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread2 is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread2 is done");
countDownLatch.countDown();
}
});
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread3 is running");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread3 is done");
countDownLatch.countDown();
}
});
thread1.start();
thread2.start();
thread3.start();
countDownLatch.await();
System.out.println("All threads are done");
}
}
在这个例子中,我们使用了CountDownLatch来使线程等待多个其他线程全部完成后再执行。我们初始化了CountDownLatch的计数器为3,也就是说有3个线程需要等待。每个线程在完成任务后都会把CountDownLatch的计数器减1。主线程在调用await方法后会一直等待,直到计数器变为0。当计数器变为0时,主线程就会继续执行,并打印“All threads are done”。
总结
CountDownLatch是一个非常方便的同步工具,可以帮助我们等待一个或多个线程完成后再继续执行。在上面的示例中,我们演示了如何使用CountDownLatch在一组线程中等待某个线程完成后再继续执行,以及如何等待多个线程全部完成后再继续执行。在实际开发中,CountDownLatch经常被用于复杂的多线程应用程序中,可以提高代码的可读性和可维护性。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java多线程之同步工具类CountDownLatch - Python技术站