不能,可以在其中加一个sleep()测试下,因为每次value的是变的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();
}
}
}结果打印的都是100,如果是同步的话应该是从1到100
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();
}
}
}结果打印的都是100,如果是同步的话应该是从1到100
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();
}
}
}这样就没问题了