zoukankan      html  css  js  c++  java
  • 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++;
                }
            }
        }
  • 相关阅读:
    企业在线学习平台开发02
    企业在线学习平台开发01
    20200807-1
    20200801-01
    16用户体验评价-补
    13第一阶段意见评审-补
    11单词统计-补
    09用户模板和用户场景-补
    08顶会热词统计-补
    时间 Java
  • 原文地址:https://www.cnblogs.com/lifehrx/p/5785880.html
Copyright © 2011-2022 走看看