日期:2014-05-20 浏览次数:20866 次
public class test {
private static Integer value = 0;
public static int getValue() {
synchronized (value) {
++value;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
public void run() {
System.out.println(getValue());
}
}).start();
}
}
}
public class test {这样就没问题了
private static Integer value = 0;
static Object obj = new Object();
public static int getValue() {
synchronized (obj) {
++value;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
public void run() {
System.out.println(getValue());
}
}).start();
}
}
}