1、代码示例
public class TestSyncro {
public static void main(String[] args) {
Person testP = new Person();
Thread1 t1 = new Thread1(testP);
Thread2 t2 = new Thread2(testP);
t1.start();
t2.start();
}
}
class Thread1 extends Thread {
private Person curPerson = null;
public Thread1(Person person){
this.curPerson = person;
}
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " call start");
curPerson.display();
System.out.println(Thread.currentThread().getName() + " call end");
}
}
class Thread2 extends Thread {
private Person curPerson = null;
public Thread2(Person person){
this.curPerson = person;
}
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " call start");
curPerson.display();
System.out.println(Thread.currentThread().getName() + " call end");
}
}
class Person{
public synchronized void display(){
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName() + " " + i);
try{
Thread.sleep(2000); // sleep是Thread类静态方法,不会释放对象锁
}catch(Exception ex){
}
if(i==3){
try{
this.wait(2000); // wait是Object类实例方法,会释放对象锁
}catch(Exception ex){
}
}
}
}
}
2、执行结果
Thread-0 call start
Thread-0 1
Thread-1 call start
Thread-0 2
Thread-0 3
Thread-1 1
Thread-1 2
Thread-1 3
Thread-0 4
Thread-0 5
Thread-0 call end
Thread-1 4
Thread-1 5
Thread-1 call end
3、结果分析
(1)Thread-0执行打印1,2,3期间,都有调用sleep方法,但是Thread-1并没有机会执行,说明sleep没有释放对象锁;
(2)Thread-0执行到打印3时,调用了wait方法,这时Thread-1执行了,说明wait释放了对象锁