}
模拟田径赛跑 – 裁判鸣枪
import java.util.Random;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) {
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch endLatch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
public void run() {
try {
startLatch.await();
System.out.println(Thread.currentThread().getName()+" 起跑,冲刺");
Thread.sleep(new Random().nextInt(3000)+1000);
System.out.println(Thread.currentThread().getName()+" 到达终点");
endLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(3000);
System.out.println("裁判,鸣枪开始!");
startLatch.countDown();
endLatch.await();
System.out.println("裁判,比赛结束,宣布结果!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
线程之间交换数据 – 买卖双方约定交易地点交易
import java.util.Random;
import java.util.concurrent.Exchanger;
public class ExchangerDemo {
public static void main(String[] args) {
final Exchanger<String> exchanger = new Exchanger<String>();
new Thread(new Runnable() {
public void run() {
try {
System.out.println("买家拿钱出发");
Thread.sleep(new Random().nextInt(5000)+1000);
System.out.println("买家到达交易地点,等待卖家");
System.out.println("买家拿到了"+exchanger.exchange("钱"));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
System.out.println("卖家拿货出发");
Thread.sleep(new Random().nextInt(5000)+1000);
System.out.println("卖家到达交易地点,等待买家");
System.out.println("卖家拿到了"+exchanger.exchange("货"));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}