代码如下,注释写的非常详细,复制就能跑。
public class Xs02 {
//用volatile修饰了两个一会要用到的int
private volatile int flag=0;
private volatile int work=0;
private Thread t1,t2,t3;
public static void main(String[] args) {
Xs02 xs02 = new Xs02();
//启动
xs02.ts();
}
private void ts(){
//启动线程的方法,这一步直接写在main方法也行
t1=new Thread(new a());
t2=new Thread(new b());
t3=new Thread(new c());
t1.start();
t2.start();
t3.start();
}
private class a implements Runnable{
@Override
public void run() {
//先判断要打印的数字是否达到阈值,没有才继续打印
while (work<=100){
//这里是用volatile给每个线程都做了一个专属标志位,只有该变量为指定值时,对应的线程才打印数字
if(flag==0){
//如果为指定值就打印数字
System.out.println("1:"+work++);
//打印完后,修改为下一个线程的标志位
flag=1;
}
}
}
}
private class b implements Runnable{
@Override
public void run() {
while (work<=100){
if(flag==1){
System.out.println("2:"+work++);
flag=2;
}
}
}
}
private class c implements Runnable{
@Override
public void run() {
while (work<=100){
if(flag==2){
System.out.println("3:"+work++);
flag=0;
}
}
}
}
}