目录
解法3 静态变量 ReentrantLock Condition
注意:本文参考 面试题精选:两个线程按顺序交替输出1-100 - xindoo - 博客园
具体题目是这样的,两个线程交替按顺序输出1-100,第一个线程只能输出偶数,第二线程输出奇数,想象下两个小孩轮流喊数。
两个线程交替输出,这就意味着它俩是需要协同的,协同意味着二者之间要有信息传递,如何相互传递信息? 你可能直接想到,既然是0-100的数按顺序交替输出,那么每个进程只需要时不时看看计数器的值,然后看是否轮到自己输出了就行。没错,这就是解法一的思路。
解法1 静态原子变量 死循环
有了上面的思路,你肯定能快速写出以下代码:
public class PrintNumber extends Thread {
private static int cnt = 0;
private int id; // 线程编号
public PrintNumber(int id) {
this.id = id;
}
@Override
public void run() {
while (cnt < 100) {
while (cnt%2 == id) {
cnt++;
System.out.println("thread_" + id + " num:" + cnt);
}
}
}
public static void main(String[] args) {
Thread thread0 = new PrintNumber(0);
Thread thread1 = new PrintNumber(1);
thread0.start();
thread1.start();
}
}
但当你实际运行后会发现!!!
thread_0 num:1
thread_0 num:3
thread_1 num:3
thread_1 num:5
thread_1 num:6
thread_0 num:5
thread_0 num:8
thread_0 num:9
thread_1 num:8
thread_0 num:11
thread_1 num:11
.........
不仅顺序不对,还有重复和丢失!问题在哪?回到代码中cnt++; System.out.println("thread_" + id + " num:" + cnt);
这两行,它主要包含两个动作,cnt++
和输出,当cnt++