我不主张用全局的,但如果你一定要,你可以不喜欢以下。一般来说:让每个线程建立自己的数据。完成其工作后,将其数据添加到同步的全局集合中(本例中为List<List<String>>
)。然后在所有线程完成工作后再读取该收集。
全球收集的数据:
public class GlobalDataBroker {
public static List<List<String>> data = Collections.synchronizedList(new LinkedList<List<String>>());
}
的范例:
public static void main(String[] args) throws InterruptedException {
for (int i=0; i < 10; i++) {
new Thread(new Runnable(){
@Override
public void run() {
List<String> list = new LinkedList<String>();
list.add(String.format("I'm a Thread and my name is %s.",Thread.currentThread()));
for (int i = 0; i < 5; i++) {
list.add("Data!");
}
GlobalDataBroker.data.add(list);
}
}).start();
}
// When the threads are done ...
Iterator<List<String>> i = GlobalDataBroker.data.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
输出:
[I'm a Thread and my name is Thread[Thread-8,5,main]., Data!, Data!, Data!, Data!, Data!]
[I'm a Thread and my name is Thread[Thread-5,5,main]., Data!, Data!, Data!, Data!, Data!]
...
[I'm a Thread and my name is Thread[Thread-7,5,main]., Data!, Data!, Data!, Data!, Data!]
请注意,你只应该开始遍历数据,一旦你已经完成了写作。 (否则,您可能会遇到可怕的ConcurrentModificationException
。)
有什么问题? – MaVRoSCy
为什么你想*全局变量? – oldrinb
如果您担心数组的大小,请使用列表? –