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

时间:2016-11-14 22:50:28

标签: java multithreading list arraylist

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

//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声明为由构造函数指定的volatile字段。

更新: 好吧,我做了一个更简单的程序,用一个简单的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;
    }

}

为什么主线程中的整数值没有更新?

2 个答案:

答案 0 :(得分:0)

这与多线程无关,只是变量范围。 Folderpath="c:\windows" 类中的i未在Threading MyCustomRunnable方法中更新。

答案 1 :(得分:0)

添加

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

到你的线程类和你的runnable add

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