当前位置: 代码迷 >> J2EE >> 这是什么原因,多线程变量同步的有关问题
  详细解决方案

这是什么原因,多线程变量同步的有关问题

热度:272   发布时间:2016-04-17 23:34:08.0
这是什么原因,多线程变量同步的问题
本帖最后由 adadadadadadadc 于 2014-11-07 09:28:36 编辑

public class Test implements Runnable {

       public static void main(String[] args) throws Exception {
               String[] ss = {"a", "b"};
for (String s : ss) {
new Thread(new Test(s)).start();
}
}

       public void run() {
try {
System.out.println(id);
Thread.sleep(1000);
throw new Exception("异常");
} catch (Exception e) {
idsTemp.put(id , id);
System.out.println("idsTemp.size(): " + idsTemp.size());
}
}
}



Thread.sleep();时间一样基本上都是输出
a
b
idsTemp.size(): 1
idsTemp.size(): 1


要是我这边没有Thread.sleep(); 都输出
a
b
idsTemp.size(): 2
idsTemp.size(): 2

请问要怎么达到下面这样正常的效果
a
b
idsTemp.size(): 1
idsTemp.size(): 2

------解决思路----------------------
idsTemp.加static synchronized(最好这个也加上)
  相关解决方案