package chapter3.test3_1.test3_1_11;
public class MyService {
private Object lock = new Object();
public void waitMethod() {
try {
synchronized (lock) {
System.out.println("begin wait() ThreadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis());
lock.wait();
System.out.println(" end wait() ThreadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void notifyMethod() {
try {
synchronized (lock) {
System.out.println("begin notify() ThreadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis());
lock.notify();
Thread.sleep(5000);
System.out.println(" end notify() ThreadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
类MyThreadA.java
package chapter3.test3_1.test3_1_11;
public class MyThreadA extends Thread {
private MyService myService;
public MyThreadA(MyService myService) {
super();
this.myService = myService;
}
@Override
public void run() {
myService.waitMethod();
}
}
MyThreadB.java代码
package chapter3.test3_1.test3_1_11;
public class MyThreadB extends Thread {
private MyService myService;
public MyThreadB(MyService myService) {
super();
this.myService = myService;
}
@Override
public void run() {
myService.notifyMethod();
}
}
类Test.java代码
package chapter3.test3_1.test3_1_11;
public class Test {
public static void main(String[] args) throws InterruptedException {
MyService myService = new MyService();
MyThreadA a = new MyThreadA(myService);
a.start();
Thread.sleep(50);
MyThreadB b = new MyThreadB(myService);
b.start();
}
}
程序运行结果
notify()方法执行后锁不释放
通过对控制台输出的时间的分析,可以总结出:必须 执行完 notify() 方法所在的同步 synchronized代码块后才释放锁。



