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

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

public class ThreadTest { private static int i = 1; private static boolean lock = false; private static Runnable runnable1 = () -> { while(i <= 10){ if (!lock) { System.out.println(Thread.currentThread().getName() + "" + i++); lock = true; } } }; private static Runnable runnable2 = () -> { 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(); } }


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

    推荐阅读