【发布时间】:2022-01-04 20:35:57
【问题描述】:
我有两个方法在一个线程中同时工作,我能够从 Loader 类访问 访问变量和计数器变量 到 Load 类。
我想要的是当 while 循环在 Loader 类 上更新时,能够访问 Load 类 的更新,因为我想使用更新后的变量.
有可能吗?如果可以,我该怎么做?
class Loader extends Thread {
int access = 0;
int counter = 0;
public void run() {
while (access < 5) {
// System.out.println("Hello " + access);
System.out.println("counterA is " + counter);
access++;
counter++;
}
}
class Load extends Thread {
public void run() {
int me = 0;
Loader acc = new Loader();
Loader cou = new Loader();
int result = acc.access;
int counterB = cou.counter;
//cannot get the result and counterB outside a loop
if (counterB == 3) {
System.out.println("Access " + result);
System.out.println("counterB is " + counterB);
}
//cannot get the result and counterB inside a loop
while (me < 5) {
if (counterB == 3) {
System.out.println("Access " + result);
System.out.println("counterB is " + counterB);
}
me++;
}
}
}
class MyClass {
public static void main(String[ ] args) {
Loader obj = new Loader();
Load o = new Load();
obj.start();
o.start();
}
}
【问题讨论】:
-
请edit发帖并正确格式化代码。
-
您需要将要访问的变量作为字段,而不是局部变量。您还需要
Loader对象引用Load对象,以便它可以找到您要更新的字段。 -
这听起来你需要使用
Observer模式来解决这个问题。此外,如果您需要观察int字段的变化,则需要改用AtomicInteger。 -
谁能给我一个示例代码
标签: java multithreading while-loop