在不同线程中填充的列表在调用线程-Java中显示为空
我的代码基本上是这样的:在不同线程中填充的列表在调用线程-Java中显示为空,java,multithreading,list,arraylist,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();
//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
为什么主线程中的整型值没有更新?这与多线程无关,只是变量作用域<
Threading
类中的code>i不会在mycustomrunable
的run
方法中更新。这与多线程无关,只是变量作用域<Threading
类中的code>i未在MyCustomRunnable
的run
方法中更新。添加
public static void setI(int i) {
Threading.i = i;
}
添加到线程类和可运行添加中
public void run() {
this.i = 1;
Threading.setI(1);
}
加
添加到线程类和可运行添加中
public void run() {
this.i = 1;
Threading.setI(1);
}
你能显示所有相关代码吗?列表在哪里填充?能否从
MyCustomRunnable
添加代码?只要MyCustomRunnable
中的run()
方法正在填充myList
它就应该反映在父线程中。您能显示所有相关的代码吗?列表在哪里填充?能否从MyCustomRunnable
添加代码?只要MyCustomRunnable
中的run()
方法正在填充myList
它就应该反映在父线程中。