我已经多次测试以下代码,并且始终打印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;