代码实现如下:
public class Test{
int i = 0;
public static void main(String[] args){
Test test = new Test();
new Thread(test::print1).start();
new Thread(test::print2).start();
}
public synchronized void print1(){
while (i<=100){
System.out.println("A:"+i);
i++;
this.notify();
try{
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
}
public synchronized void print2(){
while (i<=100){
System.out.println("B:"+i);
i++;
this.notify();
try{
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
输出结果如下:
A:0
B:1
A:2
B:3
A:4
B:5
A:6
B:7
A:8
B:9
A:10
.
.
.
B:97
A:98
B:99
A:100
参考文章:Java实现两个线程交替打印的功能