当多个线程需要执行时,若其中一个或多个线程需要等待其他线程完成某些操作后才能执行,则可用CountDownLatch实现功能。
public class CountDownLatchTest {
static CountDownLatch c = new CountDownLatch(2);
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(1);
c.countDown();
System.out.println(2);
c.countDown();
}
}).start();
c.await();
System.out.println("3");
}
}
复制代码
当多个线程到达屏障时将会被阻塞,只有这些线程的最后一个线程到达屏障后,屏障才会开门,所有被屏障拦截的线程才能继续执行,并且该屏障是可重复使用的。
public class CyclicBarrierTest {
static CyclicBarrier c = new CyclicBarrier(2);
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
try {
c.await();
} catch (Exception e) {
}
System.out.println(1);
}
}).start();
try {
c.await();
} catch (Exception e) {
}
System.out.println(2);
}
}
复制代码
当有m个线程,n个资源(m > n且每个线程占用一个资源)时,Semaphore可用来控制同时访问资源的线程数量,以保证合理地使用资源。
public class SemaphoreTest {
Semaphore semaphore = new Semaphore(3);
public static void main(String[] args) {
for ( int i=0; i<10; i++ ) {
new Thread( new Runnbale(){
public void run(){
semaphore.acquire();
//这里执行任务代码
semaphore.release();
}
} ).start();
}
}
}
复制代码