public class 线程间通信 {
private volatile static boolean a = true;
public static void main(String[] args) {
//开启线程
new Thread(new Runnable() {
@Override
public void run() {
read();
}
}).run();
//a赋值
a = false;
}
private static void read() {
while (a) {
System.out.println("a=" + a);
}
}
}
以上代码当执行到a=false时,线程应该接受并退出循环,但是实际上线程并未执行到,会一直执行下去,不会停止,大神帮忙分析一下原因
正如上面所说,你这只是单线程,不是双线程。程序按顺序执行到read(),a一直为true。while就是一个死循环,没有退出条件。要使用双线程,要用start方法。
线程一旦启动,只能在线程里面进行赋值,外面的操作不受控制。听过【将在外君令有所不受】吗?
private volatile static boolean a = true;
private static int index = 0;
public static void main(String[] args) {
//开启线程
new Thread(new Runnable() {
@Override
public void run() {
read();
}
}).run();
//a赋值
a = false;
}
private static void read() {
while (a) {
index++;
System.out.println("a=" + a);
// 加入自己退出的条件,例如执行10次就退出
if(index>=10){
System.out.println("index=" + index);
a = false;
}
}
}
run是在主线程运行Thread。。你两个都在主线程,while循环阻塞了。改成start,新开一个线程执行就可以了。