我有两条线
t1
和
t2
. 他们只在
total
整数变量。但是变量
全部的
不在这些线程之间共享。我想用同样的
全部的
变量
t1级
和
t2型
线。我该怎么做?
我的
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)
}
}
两个print语句都应该给出9,但它们分别给出7和2(因为total变量不是
t1级
和
t2型
).