【发布时间】:2019-05-11 09:26:38
【问题描述】:
假设我有这样的代码:
class A extends Thread {
Thread t = new Thread();
private static int id = 0;
A(){
id++;
this.t.start();
}
private synchronized static int getId() { return id; }
public void run() { System.out.println(getId()); }
}
public class Test throws InterruptedException {
public static void main(String[] args) {
A thread1 = new A();
A thread2 = new A();
try {
thread1.t.join();
thread2.t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread ends here");
}
}
我期待这样的输出:
1
2
但是输出是:
2
2
我应该在这里做什么?感谢帮助。问。
【问题讨论】:
-
private static volatile int id = 0; -
volatile不够,++不是原子的:stackoverflow.com/questions/25168062/why-is-i-not-atomic -> 使用AtomicInteger。 -
为什么你的
Thread里面有一个Thread?此外,永远不要extends Thread- 这会产生各种奇怪的行为,请使用Runnable。你永远不会启动你的A实例;你启动了一个内部Thread,它什么都不做。您在 ctor 中增加变量而不是在run()方法中。这段代码几乎在所有方面都是错误的 - 请先阅读有关 Java 线程的基本教程。 -
谢谢,我必须解决。问。
-
此代码无法编译。 getId 方法在类 Thread 中定义,它返回一个 long,而不是 int。
标签: java multithreading