[英]Java Thread, change value in thread from main
With the thread class defined below, if the main calls the thread by: 使用下面定义的线程类,如果主线程通过以下方式调用线程:
Thread foo = new aThread1();
foo.start();
Is it possible to change the value of xxx from the calling class? 是否可以从调用类更改xxx的值? It was simple to change variables while in the thread OF the main class, but I can't seem to go the other way.
在主类的线程中更改变量很简单,但是我似乎没有其他选择。
class aThread1 extends Thread {
volatile static int xxx = 1;
public void run() {
try {
sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Current value: " + xxx);
}
}
Declare the field as public
将字段声明为
public
public volatile static int xxx = 1;
And from any code: 并从任何代码:
aThread1.xxx = 2;
Use AtomicInteger and pass it as a reference to the thread (ie aThread1) from main. 使用AtomicInteger并将其作为对main线程(即aThread1)的引用。 You also need to handle the InterruptedException properly .
您还需要正确处理InterruptedException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.