【问题标题】:Java need help in threads/ code compiling debuggingJava在线程/代码编译调试方面需要帮助
【发布时间】:2015-02-28 13:40:23
【问题描述】:

问题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();

它们是按顺序工作的(就像第一个线程先工作,然后是第二个线程)还是随机运行。 谢谢

【问题讨论】:

  • Java Thread Example?的可能重复
  • 不,我刚刚再次发布,因为它几乎相同,但这是另一个问题,因为它带有线程......并且工作方式不同。
  • 我试图编辑它,他们告诉我你不能在已经回答的第一个问题中添加另一个问题..

标签: java multithreading compilation


【解决方案1】:
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 个线程(当前、衍生线程 1、衍生线程 2)之间没有同步。

【讨论】:

  • 感谢第二个问题 :) 对于我的解决方案中的第一个问题,它说 1 或 2 然后是 2,类似的解决方案不会出错
  • 是的,它可以是 (2,2),或者如果 thread1 第一个完成 before 第二个 new Example5,它可以是 (1,2)
  • 所以如果线程 2 启动然后线程 1 打印 (2,2),因为 a 是静态的?
  • 如果 thread2 已启动,则意味着 ex2 已被实例化,因此 a=2。但是你必须知道像System.out.println() 甚至a++ 这样的操作不是原子的。由于您仅在当前线程中增加a,因此您最后总是会有 2,但如果您打算在生成的线程中执行此操作(没有足够的同步),您最终可能会得到其他结果......
猜你喜欢
  • 2011-10-04
  • 2011-08-22
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-22
相关资源
最近更新 更多