zoukankan      html  css  js  c++  java
  • java中断线程的两种方式

    方式一:使用interrupt

    public static void main(String[] args) {
            MyRunable myRunable = new MyRunable();
            Thread thread = new Thread(myRunable);
            thread.start();
            for (int i = 0;i < 50;i++){
                System.out.println(Thread.currentThread().getName()+"-"+i);
                try {
                    Thread.sleep(300);          //线程休眠,会让出cpu时间片(让同一进程中其余线程占用cpu时间片)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(i == 20){
                    thread.interrupt();             //在自定义线程上打了一个中断标记
                }
            }
        }
    class MyRunable implements Runnable{
    
        @Override
        public void run() {
            for (int i = 0;i< 50;i++){
                if(Thread.interrupted()){      //interrupted方法会清除中断标记
                    break;
                }
                System.out.println(Thread.currentThread().getName()+"-"+i);
                try {
                    Thread.sleep(300);        //sleep方法也会清除中断标记并报错
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();        //在报错的地方继续添加中断标记在循环判断的时候会中断该循环
                }
            }
        }
    }

    方式二:使用中断标记(更常用,更好理解)

    public static void main(String[] args) {
            MyRunable myRunable = new MyRunable();
            Thread thread = new Thread(myRunable);
            thread.start();
            for (int i = 0;i < 50;i++){
                System.out.println(Thread.currentThread().getName()+"-"+i);
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(i == 20){
                    myRunable.flag = false;
                }
            }
        }
    class MyRunable implements Runnable{
        public boolean flag = true;
        
        @Override
        public void run() {
            int i = 0;
            while (flag){
                System.out.println(Thread.currentThread().getName()+"-"+(i++));
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 相关阅读:
    LibreOJ #507. 「LibreOJ NOI Round #1」接竹竿
    BZOJ 4590: [Shoi2015]自动刷题机
    luogu P3808 【模板】AC自动机(简单版)
    cogs 2569. [東方] 博丽灵梦 梦想妙珠
    codeforces 1C. Ancient Berland Circus
    BZOJ 4570: [Scoi2016]妖怪
    HDU 1392 Surround the Trees
    cogs 999. [東方S2]雾雨魔理沙
    Uva 10652 Board Wrapping
    AC日记——[Sdoi2008]Cave 洞穴勘测 bzoj 2049
  • 原文地址:https://www.cnblogs.com/wscw/p/14512767.html
Copyright © 2011-2022 走看看