填充在不同线程中的列表在调用者线程中显示为空-Java

randomDude

我的代码基本上是这样的:

//in Main Thread:              (myList is a volatile field)
myList = new ArrayList<myClass>();
Thread myThread = new Thread(new MyCustomRunnable(myList));
myThread.start();
//some lines of code NOT involving myList
myThread.join();
//myList appears empty here even though I can see that the list has been populated 
//in the other thread

有这种现象的原因吗?就像我说的那样,我可以在调试器中看到已在被调用线程中填充了列表,但是这些更改未在join()方法之后的调用者线程中出现。MyCustomRunnable也将ArrayList声明为由构造函数分配的易失字段。

更新:好的,我做了一个简单的程序,用一个简单的Integer替换了ArrayList,结果是一样的...

public class Threading {
    private volatile static Integer i = 0;
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new MyCustomRunnable(i));
        t.start();

        t.join();
        System.out.println(i);    //prints '0', I expected '1'
    }
}

public class MyCustomRunnable implements Runnable {
    private volatile Integer i;

    public MyCustomRunnable(Integer i) {
        this.i = i;      
    }

    public void run() {
        this.i = 1;
    }

}

为什么在主线程中不更新Integer的值?

bhavya.work

添加

public static void setI(int i) {
  Threading.i = i;
}

到您的Threading类并在您的runnable中添加

public void run() {
  this.i = 1;
  Threading.setI(1);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章