这是一道常见的面试题,我使用了三种方法来实现
方法一 两线程交替打印
private static int count = 100;
private static boolean flag = true;
new Thread(() -> {
while (count <= 200){
if (flag == true){
System.out.println(Thread.currentThread().getName() + " " + count++);
flag = false;
}
}
}).start();
new Thread(() -> {
while (count <= 200){
if (flag == false){
System.out.println(Thread.currentThread().getName() + " " + count++);
flag = true;
}
}
}).start();
方法二 CountDownLatch
注意
while(true)
循环
CountDownLatch countDownLatch = new CountDownLatch(100);
for (int i = 100; i < 200; i++) {
int finalI = i;
new Thread(() -> {
//为什么要加 while(true) 循环:
//线程启动后不一定立即执行,也就是会导致线程乱序执行
//乱序的线程执行完一次if判断后就不再执行了
System.out.println(Thread.currentThread().getName() + " NOW RUNNING");
while (true){
if (finalI == 200 - countDownLatch.getCount()){
System.out.println(Thread.currentThread().getName() + " " + finalI);
countDownLatch.countDown();
break;
}
}
}).start();
}
方法三 Semaphore 信号量
Semaphore semaphore = new Semaphore(1);
for (int i = 100; i < 200; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " " + count);
count++;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}).start();
}
- Post link: http://example.com/2022/02/02/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%AE%9E%E7%8E%B0100%E5%88%B0200%E9%A1%BA%E5%BA%8F%E6%89%93%E5%8D%B0/
- Copyright Notice: All articles in this blog are licensed under unless otherwise stated.