public class Starter extends Thread
{
        private int x = 2;
        public static void main(String[] args) throws Exception
        {
           Starter a= new Starter();
           a.makeItSo();
        }
        public Starter()
        {
            x = 5;
            start();
        }
        public void makeItSo() throws Exception
        {
         System.out.println(Thread.currentThread().getName()+"------------->");
            join();
            x = x - 1;
            System.out.println(x);
        }
        public void run()
        {
         System.out.println(Thread.currentThread().getName()+"------------->");
         x *= 2;
        }
 }   答案是9  我认为答案不确定
我的理解是   如果makeitso的线程  和run的线程 都在可运行状态  但是JVM万一先挑选了makeitso的话 而且有join(),会等到该程序运行结束才执行run的代码  就是输出4了   有哪位高手可以请教一下?  谢谢

解决方案 »

  1.   

    注意join方法
    public class Starter extends Thread
    {
      private int x = 2;
      public static void main(String[] args) throws Exception
      {
      Starter a= new Starter();
      a.makeItSo();
      }
      public Starter()
      {
      x = 5;
      start();
      }
      public void makeItSo() throws Exception
      {
      System.out.println(Thread.currentThread().getName()+"------------->");
      join();/////////////等待该线程终止。
      
      x = x - 1;
      System.out.println(x);
      }
      public void run()
      {
      System.out.println(Thread.currentThread().getName()+"------------->");
      x *= 2;
      }
     }
      

  2.   

    run()方法和makeItSo()方法的执行顺序是不确定的,但是x的值的计算顺序是确定的。因为join()方法暂停了main线程的执行.