1、问题描述
用程序实现两个线程交替打印0-100的奇偶数
2、 解题思路
让线程1打印之后唤醒其他线程,然后让出锁,自己进入休眠状态,因为进入了休眠状态就不会与其他线程争抢锁,此时只有线程2能获取锁,线程2以同样的逻辑执行,唤醒线程1并让出持有的锁,自己进入休眠状态。
代码
private int count = 0;
private final Object lock = new Object();
public void turning() throws InterruptedException {
Thread even = new Thread(() -> {
while (count <= 100) {
synchronized (lock) {
System.out.println("偶数: " + count++);
lock.notifyAll();
try {
if (count <= 100) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread odd = new Thread(() -> {
while (count <= 100) {
synchronized (lock) {
System.out.println("奇数: " + count++);
lock.notifyAll();
try {
if (count <= 100) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
even.start();
Thread.sleep(1);
odd.start();
}
public class TurningRunner implements Runnable {
private int count=0;
private final Object lock = new Object();
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + ": " + count++);
lock.notifyAll();
try {
if (count <= 100) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
|