2个线程依次打印出1到10的数

时间:2022-09-28 18:31:23

之前想用wait()和notify的机制来做,没有成功。给一个lock信号量就可以了。



public class ThreadTest {


public static int i = 1;

public static boolean lock = false;

public static Runnable runnable1 = new Runnable() {

public void run() {


while(i <= 10){
if (!lock) {
System.out.println(Thread.currentThread().getName() + "    " + i++);
lock = true;
}
}
}
};

public static Object object = new Object();
public static Runnable runnable2 = new Runnable() {

public void run() {


while(i <= 10){
if (lock) {
System.out.println(Thread.currentThread().getName() + "    " + i++);
lock = false;
}
}
}
};

public static void main(String[] args){
    new Thread(runnable1).start();
    new Thread(runnable2).start();
}
}