java 线程间变量共享_如何在线程之间共享变量?

我有两条线

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型

).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值