开发者

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? It was simple to change variables while in the thread OF the main class, but I can't see开发者_JAVA技巧m 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 volatile static int xxx = 1;

And from any code:

aThread1.xxx = 2;


Use AtomicInteger and pass it as a reference to the thread (i.e. aThread1) from main. You also need to handle the InterruptedException properly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜