线程交替打印1,2,3,4
思路:
- 使用锁
- 限制奇数线程结束后必须将锁给偶数线程
// 实例锁,注意lambda表达式传递的值引用必须是不可变的,因此使用数组传递数组指针,如果是实例对象也是可以的。
final Integer[] odd = {0};
Thread t1 =
new Thread(
() -> {
int num = -1;
while (num <= 1) {
if (odd[0] == 0) {
synchronized (odd){
num += 2;
System.out.println(num);
odd[0] = 1;
}
}
}
});
Thread t2 =
new Thread(
() -> {
int num = 0;
while (num <= 2) {
if (odd[0] == 1) {
synchronized (odd){
num += 2;
System.out.println(num);
odd[0] = 0;
}
}
}
});
t1.start();
t2.start();
Q.E.D.