使用lock锁
public class Main{
public static Lock lock = new ReentrantLock();
public static int i=0;
public static void main(String[] args) {
Thread th1 = new Thread("1"){
public void run(){
while(i<=100){
lock.lock();
if(i%2==1&&i<=100){
System.out.println(Thread.currentThread().getName()+" "+i);
i++;
}
lock.unlock();
}
}
};
Thread th2 = new Thread("2"){
public void run(){
while(i<=100){
lock.lock();
if(i%2==0&&i<=100){
System.out.println(Thread.currentThread().getName()+" "+i);
i++;
}
lock.unlock();
}
}
};
th1.start();
th2.start();
}
}