当前位置: 代码迷 >> Java相关 >> 关于一个线程的理解 求解,该如何解决
  详细解决方案

关于一个线程的理解 求解,该如何解决

热度:8978   发布时间:2013-02-25 21:50:53.0
关于一个线程的理解 求解
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楼的改法是正确的
------解决方案--------------------------------------------------------
呵呵 学习了
  相关解决方案