两线程交替打印数字
加锁实现
//两线程交替打印1-20
public class Main{
public static void main(String[] args){
Object lock=new Object();
final int maxNum=20;
new Thread(()->{
for(int i=1;i<maxNum;i+=2){
synchronized (lock){
System.out.print(i+" ");
lock.notify();
try {
if(i<maxNum-1){
lock.wait();
}
} catch (InterruptedException e) {}
}
}
}).start();
new Thread(()->{
for(int i=2;i<=maxNum;i+=2){
synchronized (lock){
System.out.print(i+" ");
lock.notify();
try {
if(i<maxNum){
lock.wait();
}
}catch (InterruptedException e){}
}
}
}).start();
}
}
无锁实现
//两线程交替打印1-20
public class Main{
public volatile static boolean flag=true;
public static void main(String[] args){
final int maxNum=20;
new Thread(()->{
for(int i=1;i<maxNum;i+=2){
while (!flag);
if(flag){
System.out.print(i+" ");
flag=false;
}
}
}).start();
new Thread(()->{
for(int i=2;i<=maxNum;i+=2){
while (flag);
if(!flag){
System.out.print(i+" ");
flag=true;
}
}
}).start();
}
}
最后对于while(flag);可以改写为while(flag) Thread.onSpinWait();代表flag==false时自旋。

浙公网安备 33010602011771号