只有getSeq()会改变状态,理论上,使用synchronized同步的话,多线程中获取seq的值,应该是唯一的,但测试的结果,获取的seq结果,有几个数会重复。这是什么原因导致的?
public class ThreadTest implements Runnable {
private static int seq;
public synchronized int getSeq(){
return seq++;
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadTest(),"t1");
Thread t2 = new Thread(new ThreadTest(),"t2");
t1.start();
t2.start();
}
@Override
public void run() {
for(int i = 0;i<100000;i++){
System.out.print(getSeq()+",");
}
}
}
因为你的getSeq是成员方法,synchronized锁住的是实例对象,而你在运行的时候,new出来了两个,所以就没有效果了,解决办法有两个
1.修改 getSeq() 方法,增加static修饰符
2.启动部分代码按如下修改: