多线程学习笔记(三)线程的中断

执行中断的三种方法

1.stop() 废弃方法,开发中不要使用。因为一调用,线程就立刻停止,此时有可能引发相应的线程安全性问题
2.Thread.interrupt方法
3.自行定义一个标志,用来判断是否继续执行

实例一:使用stop中断线程

public class StopDome implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new StopDome());
        thread.start();
        Thread.sleep(2000L);
        thread.stop();
    }
}

实例二:使用stop方法中断线程导致的线程不安全问题

public class UnsafeStopDome extends Thread {
    public static int i = 0;
    public static int j = 0;

    @Override
    public void run(){
        i++;
        try {
            sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        j++;
    }

    public void print()  {
        System.out.println("i的值为======》" + i );
        System.out.println("j的值为======》" + j );
    }

    public static void main(String[] args) throws InterruptedException {
        UnsafeStopDome unsafeStopDome = new UnsafeStopDome();
        unsafeStopDome.start();
        Thread.sleep(1000L);
        unsafeStopDome.print();
        unsafeStopDome.stop();//当现在执行中断时,导致了计算结果出错
    }
}

实例三:使用interrupt方法中断进程

public class InterruptDome implements Runnable{
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            System.out.println(Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new InterruptDome());
        thread.start();
        Thread.sleep(1000L);
        thread.interrupt();//会为线程打上,线程中断的标记,待线程运行完成以后,执行中断
    }
}

实例四:使用flag标志位结束进程

public class FlagDome implements Runnable {
    public static volatile boolean FLAG = true;

    @Override
    public void run() {
        while (FLAG){
            System.out.println(Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new FlagDome());
        thread.start();
        Thread.sleep(1000L);
        FLAG=false;
    }
}

 

posted @ 2019-09-20 10:51  卖单词谋生  阅读(190)  评论(0编辑  收藏  举报