[英]How to share a variable among the threads?
我有两个名为t1
和t2
线程。 他们只对total
整数变量进行加法。 但是变量total
不在这些线程之间共享。 我想在t1
和t2
线程中使用相同的total
变量。 我怎样才能做到这一点?
我的Adder
可运行类:
public class Adder implements Runnable{
int a;
int total;
public Adder(int a) {
this.a=a;
total = 0;
}
public int getTotal() {
return total;
}
@Override
public void run() {
total = total+a;
}
}
我的主课:
public class Main {
public static void main(String[] args) {
Adder adder1=new Adder(2);
Adder adder2= new Adder(7);
Thread t1= new Thread(adder1);
Thread t2= new Thread(adder2);
thread1.start();
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(adder1.getTotal()); //prints 7 (But it should print 9)
System.out.println(adder2.getTotal()); //prints 2 (But it should print 9)
}
}
两个打印语句都应该给出 9 但它们分别给出 7 和 2(因为 total 变量不是t1
和t2
)。
最简单的方法是使total
static
以便在所有Adder
实例之间共享。
请注意,这种简单的方法对于您在此处共享的main
方法就足够了(它实际上并没有并行运行任何东西,因为每个线程在启动后立即被join
)。 对于线程安全的解决方案,您需要保护添加,例如,通过使用AtomicInteger
:
public class Adder implements Runnable {
int a;
static AtomicInteger total = new AtomicInteger(0);
public Adder(int a) {
this.a = a;
}
public int getTotal() {
return total.get();
}
@Override
public void run() {
// return value is ignored
total.addAndGet(a);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.