有个 java 同步的问题,我是用 一个字符串 作为 synchronized 锁住的对象。代码 如下
import java.util.ArrayList;
import java.util.Date;
class Locktest{
private int i = 10;
}
class Lock{
private int id = 10;
private String s1 = "zhaoli";
private Locktest lockTest = new Locktest();
public void doIt() throws InterruptedException{
synchronized (this.s1) {
Thread.currentThread().sleep(10*1000);
System.out.println(Thread.currentThread().getName()+"---"+new Date());
}
}
}
public class Test {
public static void main(String[] args) {
Lock lock1 = new Lock();
Lock lock2 = new Lock();
MyThread t1 = new MyThread(lock1);
MyThread t2 = new MyThread(lock1);
MyThread t3 = new MyThread(lock2);
MyThread t4 = new MyThread(lock2);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class MyThread extends Thread{
private Lock lock = null;
public MyThread(Lock lock){
this.lock = lock;
System.out.println("lock is ----"+ lock);
}
@Override
public void run() {
super.run();
while(true){
try {
this.lock.doIt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
有一点不明白,锁住的是synchronized (this.s1) t1 t2的字符串s1 是一样的,t3,t4的字符串是一样的,应该t1 t2被锁住,t3 t4 被锁住。但是 t1 t2 t3 t4都被锁住了。
|
|