java 多线程7(线程的停止)

notify(): 是很温和的唤醒线程的方法,它不可以指定清除哪一个异常

interrupt(): 粗暴的方式,强制清除线程的等待状态,被清除的线程会接收到一个InterruptedException异常。(例:d.interrupt()方法是无法直接阻止的,要加循环)

它可以指定清除,某一个异常。

public class EX10 {
    public static void main(String[] args) {
        boolean flag = true;
        Demo d = new Demo("MMMMMMM");
        d.start();

        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " : " + i);
           if(i == 80 || i == 90){
               d.flag = flag;
               synchronized (d) {
                  // d.notify();
                   try {
                       d.interrupt();
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
           }
        }
    }
}
    class Demo extends Thread {
        boolean flag = true;
        public Demo(String s){
        }

        @Override
        public synchronized   void run() {
            int i = 0;
            while (flag) {
                try {
                    this.wait();
                } catch (InterruptedException e) {//这里会抛异常的InterruptedExcetion
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+ " :------------ " + i);
                i++;
            }
        }
    }
原文地址:https://www.cnblogs.com/lifehrx/p/5785880.html