62,635
社区成员




package concurrentutil;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3);
new Thread(()->{
try {
System.out.println("t1 ready");
TimeUnit.SECONDS.sleep(2);
System.out.println("t1 ok");
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("t1 go");
}).start();
new Thread(()->{
try {
System.out.println("t2 ready");
TimeUnit.SECONDS.sleep(1);
System.out.println("t2 ok");
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("t2 go");
}).start();
new Thread(()->{
try {
System.out.println("t3 ready");
TimeUnit.SECONDS.sleep(4);
System.out.println("t3 ok");
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("t3 go");
}).start();
}
}
CountDownLatch实现如下:
package concurrentutil;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch count = new CountDownLatch(1);
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName()+"进入等待...");
count.await();
System.out.println(Thread.currentThread().getName()+"运行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName()+"进入等待...");
count.await();
System.out.println(Thread.currentThread().getName()+"运行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
System.out.println(Thread.currentThread().getName()+"线程等待...");
TimeUnit.SECONDS.sleep(3);
count.countDown();
}
}
public static void main(String[] args) throws Exception {
Thread t1 = getThread("小明");
Thread t2 = getThread("张三");
Thread t3 = getThread("李四");
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println("全部到达终点 比赛结束");
}
private static Thread getThread(String name) {
return new Thread(name){
@Override
public void run() {
System.out.println( Thread.currentThread().getName()+" 赛车启动");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" 到达终点");
}
};
}