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

关于一个线程的理解 求解
public class TestSeven extends Thread{
  private static int x;
  public synchronized void doThings(){
  int current = x;
  current ++ ;
  x = current;
  }
  public void run(){
  this.doThings();
  }
}
class Test{
  TestSeven t1 = new TestSeven();
  TestSeven t2 = new TestSeven();
  t1.start();
  t2.start();
}

各位我想问的的是这样的一个线程类中的 doThings()方法的synchronized用了等同于没用?
t1和t2访问这个方法的时候 实际上是获得了t1和t2各自的锁??
解惑。。。谢谢

------解决方案--------------------
写错了吧?要想正确同步静态变量,得要这样
Java code
public class TestSeven extends Thread{ 
  private static int x; 
  public static synchronized void doThings(){ 
    int current = x; 
    current ++ ; 
    x = current; 
  } 
  public void run(){ 
    this.doThings(); 
  } 
}

------解决方案--------------------
synchronized 是对同一对象才有作用
而你 创建了2个对象 所以不存在同步这个问题

所以1楼的改法是正确的
------解决方案--------------------
呵呵 学习了