public class ThreadTest {
public static void main(String[] args) {
final PrintNum pn = new PrintNum(); // 使用同一个对象执行任务
new Thread(new Runnable() { // 打印奇数线程
public void run() {
for (int i = 0; i < 5; i++) { // 执行5次,即遍历100内的数
pn.printEven();
}
System.out.println("first thread stop !");
}
}).start();
new Thread(new Runnable() { // 打印偶数线程
public void run() {
for (int i = 0; i < 5; i++) {
pn.printOdd();
}
System.out.println("second thread stop !");
}
}).start();
}
}
class PrintNum {
private int cur = 0;
private boolean printOddFlag = true; // 打印odd的标志位
// 打印10个奇数
public synchronized void printOdd() {
if (!printOddFlag) {
try {
// 释放对象锁
// 线程在获取对象锁后,主动释放对象锁,同时本线程休眠
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = cur; i < cur + 20; i += 2) {
System.out.println(Thread.currentThread().getName() + ":" + i + " ");
}
printOddFlag = false;
// 对象锁的唤醒操作
// 唤醒其他所有进程(其实只有一个),线程执行到此不是立即释放对象锁,而是要退出synchronized代码块后,当前线程才会释放对象锁
this.notify();
}
// 打印10个偶数
public synchronized void printEven() {
if (printOddFlag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = cur + 1; i < cur + 1 + 20; i += 2) {
System.out.println(Thread.currentThread().getName() + ":" + i + " ");
}
cur += 20;// 偶数线程从此初始值开始
printOddFlag = true;
this.notify();
}
}