我多次测试了下面的代码,它总是打印 1,它是否正确,为什么?
public class TestThread {
static int a = 0;
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println(a);
}
};
thread.start();
a = 1;
}
}
最佳答案
这是因为应用程序不会等待线程结束来继续执行。看起来大多数时候都是做作
a = 1
比要执行的线程快。这就是为什么在某些情况下等待线程结束很重要。
如果您在 a = 1 行设置断点,您将看到打印 0。
现在试试这个:
public class TestThread {
static int a = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println(a);
}
};
thread.start();
thread.join();
a = 1;
}
}
使用join()
方法,它将等待线程完成。
您还可以使用静态 Thread.sleep 函数,但这绝对不是我建议解决此问题的方法,因为您无法确定线程完成需要多长时间。
thread.start();
Thread.sleep(100);
a = 1;
关于java - 为什么这个程序总是打印1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53633861/