• 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++;
                }
            }
        }
  • 相关阅读:
    NVI模式
    C#----接口与多继承
    C#----接口与抽象类
    C#----接口的显式实现
    C# -- 继承规则
    MVC多层架构
    BootStrap2学习日记23---弹出对话框
    APP导航设计九法
    DevExpress Grid使用checkBox选中的方法
    遗漏的SQL语句
  • 原文地址:https://www.cnblogs.com/lifehrx/p/5785880.html
Copyright © 2020-2023  润新知