日期:2014-05-20  浏览次数:20816 次

大家看看下面的代码能否实现多线程同步安全
在多线程的情况下调用下面的代码中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();
}
}
}

结果打印的都是100,如果是同步的话应该是从1到100
------解决方案--------------------
不能保证,Integer 是不可变类,在自增后会变成另外一个对象。
------解决方案--------------------
同意1楼的说法,++不是原子操作,有可能只+了一次就被其他的线程抢占,然后就会出现打印奇数的情况


------解决方案--------------------
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();          
}
}
}
这样就没问题了