简体   繁体   English

为什么该程序总是打印1

[英]Why does this program always print 1

I have tested the following code many times and it always prints 1, Is it correct and why? 我已经多次测试以下代码,并且始终打印出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;
   }
}

This is because the application doesn't wait for the thread to be over to continue its execution. 这是因为应用程序不等待线程结束以继续执行。 It seems like most of the time the affectation 似乎大多数时候

a = 1 a = 1

is faster than the thread to be executed. 比要执行的线程快。 That's why It is important in some cases to wait for your thread to be over. 这就是为什么在某些情况下等待线程结束很重要。

If you set up a breakpoint to your a = 1 line, you will see 0 is printed. 如果将断点设置为a = 1行,则会看到打印0。

Now try this : 现在尝试:

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;
   }
}

Using the join() method, It will wait for thread to be finished. 使用join()方法,它将等待线程完成。

You can also use the static Thread.sleep function but it is definitely not how I recommend to solve this issue since you can't know for sure how long it takes before your thread is complete. 您也可以使用静态Thread.sleep函数,但绝对不是建议您解决此问题的方法,因为您无法确定线程完成之前需要花费多长时间。

thread.start();
Thread.sleep(100);
a = 1;

It takes a little while to start the thread that prints the value, so the 'main' thread sets a to 1 before the system.out is reached. 启动打印该值的线程需要花费一些时间,因此“主”线程在到达system.out之前将a设置为1。 If you add a little delay before a := 1; 如果在a := 1;之前添加一点延迟a := 1; the system.out is reached before a := 1; a := 1;之前到达system.out a := 1; and then 0 is printed: 然后打印0:

    thread.start();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) { }
    a = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM