代码与这一行有没有区别?x = 5之前的行; 在Starter()方法中

Min*_*ine 1 java multithreading

// The problem in Starter() 
// with any line before x = 5 ; for example System.out.println(" Anything");
// the result "x = 4" 

// but without the result = "x = 9"
// Why??????


    public class Starter extends Thread {

    private int x = 2;

    public static void main(String[] args)
    throws Exception{


        new Starter().wakeItSo();
    }

    Starter() {

        // Next line (with or without it)
        System.out.println("anything");    


        x = 5;
        start();

    }

    public void wakeItSo()
    throws Exception{

        //join();


        x = x -1;
        System.out.println("x =  "+  x);


    }

    public void run() {
        x *=2;
    }

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

你有竞争条件.

  • 首先Starter运行的构造函数,初始化x到5然后启动一个新线程.
  • 现在有两件事发生在不同的线程中,但它们发生的顺序不确定:
    • 新线程将x的值更新为10.
    • 在主线程中,构造函数返回然后wakeItSo被调用,它访问当前值x并从中减去一个值.

如果新线程中的操作首先运行,您可能会得到结果9,如果wakeItSo首先运行,则得到4.首先发生的事情没有明确定义,并且可以在运行之间进行更改.

似乎添加print语句会减慢主线程的速度,以便x新线程中的更新更有可能首先执行.您应该知道,并不总是保证这种情况,您不应该依赖此行为.

要使程序确定地运行,您需要同步两个线程,以便第一个线程等到第二个线程完成运行(例如通过使用Thread.join).