Java在线程/代码编译调试中需要帮助

时间:2015-02-28 13:40:24

标签: java multithreading compilation

问题2: 我有几乎相同的问题,但有线程 这是代码:

public class Example5 implements Runnable {
      static int a=0;

  public Example5() {
      a++;
  }
  public int getA() {
      return (a);
  }
  public void run() {
      System.out.println(getA());
  }

  public static void main(String[] s) {
      Example5 ex1 = new Example5();
      new Thread(ex1).start();

      Example5 ex2 = new Example5();
      new Thread (ex2).start();
  }
}

它告诉我它必须打印: 1或2 2 任何人都可以在线程中解释这一点。

也有人可以向我解释当我这样做时会发生什么(与第一个问题无关)

Thread t = new Thread();
t.start();
Thread t2 = new Thread();
t2.start();

它们是否按顺序排序,(如第一个线程首先工作,然后是第二个线程),或者只是随机进行。 感谢

1 个答案:

答案 0 :(得分:0)

Example5 ex1 = new Example5(); // a = 1
new Thread(ex1).start();  // start a new thread that will execute independently from current thread

Example5 ex2 = new Example5(); // a = 2 (a is static hence shared)
new Thread (ex2).start(); // start a new thread again

// thread1 and thread2 finish (the order is not determined - could be 
// thread2 first, then thread1)
// prints: 2 2
// If Thread1 finishes before the second "new Example5()" completes
// prints: 1 2

对于最后一个问题:有点随机。由于3个线程(当前,生成的thread1,spawn thread2)之间没有同步。