gpt4 book ai didi

java - 如何在调用者的某些条件下更新 Thread 类中变量的值

转载 作者:行者123 更新时间:2023-12-02 09:09:15 26 4
gpt4 key购买 nike

假设我有两个类,一个主类和一个线程类,如下所示:

public class A {
public static void main(String []args){
int count = 0;
for(int i = 0; i < 10; i++){
count+=10;
//here on every addition, I want to update the variable countOfAdd of the thread class

//and when countOfAdd value is in multiples of 5 I want to print a statement
}
}

class B extends Thread {
int countOfAdd;
@Override
public void run(){
//on value received
count+=1;
}
}

我不知道这是否可能。如果可以的话该怎么做

提前致谢。

最佳答案

执行此操作的正常方法是队列。

创建 queue并使对它的引用可供两个线程使用。

主线程应该add()一个元素到队列中(例如增量)。

另一个线程应该poll()队列并使用此信息来更新其内部状态。

这样,线程之间就不会丢失任何中间更新。

快速但肮脏的方法是直接访问和锁定。

两个线程都可以保留对公共(public)数据 block 和公共(public)锁对象的引用(可以是 Object commonLock = new Object())。

每次任一线程需要访问数据成员时,它们都会持有锁,例如:

synchronized (commonLock) { commonCount +=1; }  // One thread.
synchronized (commonLock) { if (commonCount > 1) {...} }  // Another thread.

这很难推理,但如果每个线程中的访问次数很小,最好只有一个,则可以使用。

关于java - 如何在调用者的某些条件下更新 Thread 类中变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59540007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com