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

来源:互联网 发布:dota2饰品菠菜知乎 编辑:程序博客网 时间:2024/05/29 17:48

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

0 0
原创粉丝点击