不太好的方法:用synchronized实现
当其中一个线程一直持有锁时,会重复执行 if 判断,做无用功!
/**
* 两个线程交替打印0-100的奇偶数,
* 用synchronized关键字实现
*/
public class WaitNotifyPrintOddEvenSyn {
// 新建2个线程
// 1个只处理偶数,第二个只处理奇数(用位运算)
// 用synchronized来通信
private static int count;
private static final Object lock = new Object();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
if ((count & 1) == 0) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
}
}
}
}
}, "偶数线程").start();
new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
if ((count & 1) == 1) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
}
}
}
}
}, "奇数线程").start();
}
}
更好的实现方法:用wait和notify实现
/**
* 两个线程交替打印0-100的奇偶数,
* 用wait和notify实现
*/
public class WaitNotifyPrintOddEvenWait {
// 1.拿到锁,就打印
// 2.打印完,唤醒其它线程,自己休眠
private static int count = 0;
private static final Object lock = new Object();
static class TurningRunner implements Runnable {
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
lock.notify();
if (count <= 100) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
new Thread(new TurningRunner(), "偶数线程").start();
new Thread(new TurningRunner(), "奇数线程").start();
}
}