大家看看下面的代码能否实现多线程同步安全
在多线程的情况下调用下面的代码中test类的getValue()方法能否实现每次获取的值递增并且不重复?
public class test{
private static Integer value=0;
public static int getValue(){
synchronized(value){
++value;
return value;
}
}
}
[解决办法]
不能,可以在其中加一个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();
}
}
}
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();
}
}
}