Java concurrent
CountDownLatch 使用详解
CountDownLatch下面例子比较简单
import java.util.concurrent.CountDownLatch;
public class CountDownLatchTest {
static class SimpleThread extends Thread {
private CountDownLatch latch;
public SimpleThread(CountDownLatch latch){
this .latch = latch;
}
@Override
public void run() {
System.out.println(this + " RUNNING." );
latch.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch( 5 );
for ( int i= 0 ; i< 5 ; i++) {
new SimpleThread(latch).start();
}
latch.await();
System.out.println("Over" );
}
}
运行结果:
Thread[Thread-2 , 5 ,main] RUNNING.
Thread[Thread-0 , 5 ,main] RUNNING.
Thread[Thread-1 , 5 ,main] RUNNING.
Thread[Thread-4 , 5 ,main] RUNNING.
Thread[Thread-3 , 5 ,main] RUNNING.
Over
CyclicBarrier使用详解
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
public static class ComponentThread implements Runnable {
CyclicBarrier barrier;
int ID;
int [] array;
public ComponentThread(CyclicBarrier barrier, int [] array, int ID) {
this .barrier = barrier;
this .ID = ID;
this .array = array;
}
public void run() {
try {
array[ID] = new Random().nextInt( 100 );
System.out.println("Component " + ID + " generates: " + array[ID]);
System.out.println("Component " + ID + " sleep" );
barrier.await();
System.out.println("Component " + ID + " awaked" );
int result = array[ID] + array[ID + 1 ];
System.out.println("Component " + ID + " result: " + result);
} catch (Exception ex) {
}
}
}
public static void testCyclicBarrier() {
final int [] array = new int [ 3 ];
CyclicBarrier barrier = new CyclicBarrier( 2 , new Runnable() {
public void run() {
System.out.println("testCyclicBarrier run" );
array[2 ] = array[ 0 ] + array[ 1 ];
}
});
new Thread( new ComponentThread(barrier, array, 0 )).start();
new Thread( new ComponentThread(barrier, array, 1 )).start();
}
public static void main(String[] args) {
CyclicBarrierTest.testCyclicBarrier();
}
}
说明:在main中执行testCyclicBarrier方法
执行到CyclicBarrier barrier = new CyclicBarrier(2, new Runnable()...)时
Runnable的参数是在CyclicBarrier的数目达到2时并且所有被CyclicBarrier.await()进入等待的线程被唤醒前执行。
所以继续执行下面的两个线程
new Thread(new ComponentThread(barrier, array, 0)).start();
new Thread(new ComponentThread(barrier, array, 1)).start();
执行public void run()方法,分别执行,互不影响
执行到barrier.await();时该线程进入等待状态,当两个线程都执行完barrier.await();时,进入到new CyclicBarrier(2, new Runnable()...)里面的方法, 执行完里面的方法后,等待的两个线程再次被唤醒,继续各自执行线程后面的语句。