synchronized 获取序列值不唯一
理论上,通过synchronized修饰的方法,应该只用一条线程能访问。这样通过getSeq()得到的值应该是不重复自增的。但是测试的结果,中间会有几个重复值。这个是因为什么导致的?测试使用jdk1.6
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++){
int s = getSeq();
System.out.print(s+",");
}
}
}
天使心中黑暗
10 years, 2 months ago
Answers
在7,8行你建了两个ThreadTest, synchronized方法是根据对像(this)来上锁的,所以你有两个锁,没有起到同步的作用。
public class ThreadTest implements Runnable {
private static int seq;
private static Object lock = new Object();
public int getSeq(){
synchronized (lock) {
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++) {
int s = getSeq();
System.out.print(s+"\n");
}
}
}
monkeyx
answered 10 years, 2 months ago