- package chapter3.test3_1.test3_1_12;
-
- public class Service {
- public void testMethod(Object lock) {
- try {
- synchronized (lock) {
- System.out.println("begin wait()");
- lock.wait();
- System.out.println(" end wait()");
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- System.out.println("出现异常了,因为呈wait状态的线程被interrupt了!");
- }
- }
- }
- package chapter3.test3_1.test3_1_12;
-
- public class ThreadA extends Thread {
- private Object lock;
-
- public ThreadA(Object lock) {
- super();
- this.lock = lock;
- }
-
- @Override
- public void run() {
- Service service = new Service();
- service.testMethod(lock);
- }
- }
- package chapter3.test3_1.test3_1_12;
-
- public class Test {
- public static void main(String[] args) {
- try {
- Object lock = new Object();
- ThreadA a = new ThreadA(lock);
- a.start();
- Thread.sleep(5000);
- a.interrupt();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }

停止wait状态下的线程出现异常
1 )执行完 notify() 方法后,按照执行 wait()方法的顺序唤醒其他线程。 notify()所在的同步代码块执行完才会释放对象的锁,其他线程继续执行 wait() 之后的代码。2)在执行同步代码块的过程中,遇到异常而导致线程终止,锁也会被释放。3)在执行同步代码块的过程中,执行了锁所属对象的wait() 方法,这个线程会释放对象锁,等待被唤醒。