2个线程交替打印
突然想起以前听说的一个题目:2个线程交替打印!
自己闲来无事,想了一下需求,然后自己实现!!!
最后整理需求:2个线程交替打印一个数字从1-10。
实现思路:
- 对一个共享资源加锁。
- 某个线程获取到资源后,打印数字并+1;然后唤醒其他线程,自己则等待!
- 循环执行该逻辑,即可实现交替打印。
点击查看代码
/**
* 2个线程交替打印 1 - 10
*/
public class PrintNumber {
static int max = 10;
public static void main(String[] args) throws InterruptedException {
int threadCount = 2;
CountDownLatch count = new CountDownLatch(threadCount);
AtomicInteger number = new AtomicInteger(1);
PrintNumber printNumber = new PrintNumber();
for (int i = 0; i < threadCount; i++) {
new Thread(() -> {
printNumber.print(number);
count.countDown();
}).start();
}
count.await();
System.out.println("结束");
}
private synchronized void print(AtomicInteger number) {
while (number.get() <= max) {
System.out.println(Thread.currentThread().getName() + ": number = " + number.getAndIncrement());
this.notify();
if (number.get() <= max) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}