1. 题目
创建两个线程,打印1~n,一个线程负责打印奇数,一个负责打印偶数。
2. 思路
- 通过 wait() 和 notify() 方法实现两个线程的交替打印
- 定义几个线程共享变量,进行打印方法的控制
3. 代码
public class ThreadPrint {
static class ParityPrinter{
// n的值
private int max;
// 当前打印值
private int num=1;
// 是否打印奇数
private boolean odd=true;
public ParityPrinter(int max){
this.max = max;
}
// 打印奇数
public synchronized void printOdd(){
while (num < max){
while(!odd){
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(Thread.currentThread().getName() + " : " + num);
num++;
odd = false;
notify();
}
}
// 打印偶数
public synchronized void printEven(){
while (num < max){
while (odd){
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(Thread.currentThread().getName() + " : " + num);
num++;
odd = true;
notify();
}
}
}
public static void main(String[] args) {
ParityPrinter printer = new ParityPrinter(100);
Thread t1 = new Thread(printer::printOdd, "t1");
Thread t2 = new Thread(printer::printEven, "t2");
t1.start();
t2.start();
}
}