java 多线程访问变量,从Java中的另一个线程访问线程的变量

在Java中,不同线程间直接修改变量可能导致数据不一致。建议使用AtomicInteger等原子类来实现线程间的共享和安全操作。例如,创建一个AtomicInteger变量value,并在Runnable中分别使用它,可以确保在多线程环境下安全地进行加减操作。这样避免了线程同步问题,提高了程序的效率。
摘要由CSDN通过智能技术生成

I'm trying to access and modify a variable of a thread in another thread in java, and I really don't know how to do this.

ex :

Runnable r1 = new Runnable() {

int value = 10;

public void run() {

// random stuff

}

}

Runnable r2 = new Runnable() {

public void run() {

// of course the bellow line will not work

r1.value--; // I want here to be able to decrement the variable "value" of r1

}

}

Thread t1 = new Thread(r1);

Thread t2 = new Thread(r2);

t1.start();

t2.start();

thank you if you have any idea!

Is there any way to create a getter and setter for a thread in java?

EDIT : the answers were good, but I was not clear in my question, I will try asking a better question

解决方案

You could make it sort of work but, I suggest you use an AtomicInteger which is shared between threads.

final AtomicInteger value = new AtomicInteger(10);

Runnable r1 = new Runnable() {

public void run() {

// random stuff using value

}

}

Runnable r2 = new Runnable() {

public void run() {

value.decrementAndGet();

}

}

You can use AtomicReference for references to objects.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值