如何从多线程类中正确获取静态变量



假设我有这样的代码:


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

我应该在这里做什么?谢谢你的帮助。Q.

对于这种情况,应该使用AtomicInteger而不是int,并更改方法。

public class Test
{
public static void main(String[] args) throws InterruptedException
{
final A thread1 = new A();
final A thread2 = new A();
try
{
thread1.join();
thread2.join();
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
Thread.sleep(1000);
System.out.println("Main thread ends here");
}
public static class A extends Thread
{
private static final AtomicInteger id = new AtomicInteger(0);
A()
{
start();
}
private synchronized int getID()
{
return id.get();
}
@Override
public synchronized void run()
{
id.incrementAndGet();
System.out.println(getID());
}
}
}

最新更新