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

之前想用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();
}
}

发布了33 篇原创文章 · 获赞 2 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/zjj2006/article/details/50965685