线程一(创建 && 启动 && 中断)

悟空老师思维导图icon-default.png?t=N7T8https://naotu.baidu.com/file/07f437ff6bc3fa7939e171b00f133e17

1.实现多线程的方式有几种?

        方式一:实现Runnable接口(推荐,Java是单继承)

        方式二:继承Thread类

        实现线程通常可以分为两类,Oracle官方文档也是这样描述的;创建线程只有一种方式那就是构造Thread类,而实现线程的执行单元有两种方式;

        方法一:实现Runnable接口重写run方法并把Runnable实例传给Thread类;

        方式二:继承Thread类重写run方法

/**
 * 实现Runnable方式创建线程
 */
public class RunnableStyle implements Runnable{
    @Override
    public void run() {
        System.out.println("实现Runnable方式创建线程..");
    }

    public static void main(String[] args) {
        RunnableStyle runnableStyle = new RunnableStyle();
        new Thread(runnableStyle).start();
    }
}




/**
 * 继承Thread类方式创建线程
 */
public class ThreadStyle extends Thread{
    @Override
    public void run() {
        System.out.println("继承Thread类方式创建线程..");
    }

    public static void main(String[] args) {
        new ThreadStyle().start();
    }
}

错误观点

1.“线程池创建线程也算一种新的创建线程方式” ?

        线程池的本质也是在内部实现ThreadFactory接口使用“方式一”的形式去创建线程; 

2.“通过Callable和FutureTask创建线程也算一种新的创建线程方式” ?

        Callable和FutureTask内部都采用的是“方式一”其本质是实现Runnable接口去创建线程;

总结

        多线程实现的本质只有实现Runnable接口和继承Thread类这两种方式,其它创建线程的方式比如“线程池创建线程”,“Callable和FutureTask创建线程”都是对上面两种创建线程方式的包装虽然实现原理不同但其本质都是使用上面两种方式来创建线程的;

2.启动线程的正确和错误方式

        start()和run()方法比较;

代码演示

/**
 * 对比start方法和run方法两种启动线程的方式
 */
public class StartAndRunMethod {
    public static void main(String[] args) {
        Runnable runnable = () ->{
            System.out.println(Thread.currentThread().getName());
        };
        // run方法的形式创建线程
        runnable.run(); // 打印main,即直接调用run方法启动线程是主线程在执行

        Thread thread = new Thread(runnable);
        // start方法的形式创建线程
        thread.start(); // 打印Thread-0,调用start方法是子线程在执行
    }
}

2.1.调用start方法会做哪些操作

        1.启动新线程,并检查线程状态是否为初始化(即:threadStatus = 0);

        2.加入线程组;

        3.调用start0()方法;

2.2.调用run方法会做哪些操作

        直接调用run方法相当于就是调用了一个普通方法,即当前调用线程(主/子线程)直接调用run方法中业务逻辑,不会创建新线程加入线程组等一系列操作;

2.3.一个线程两次调用start()方法会出现什么情况?为什么?

        会抛出“IllegalThreadStateException”非法的线程状态异常,因为线程调用start()方式时会先校验当前线程的状态是否为“初始化”(即:threadStatus = 0),当threadStatus != 0时会抛出非法的线程状态异常“IllegalThreadStateException”;

2.4.既然start()方法会调用run()方法,为什么我们选择调用start()方法,而不是直接选择调用run()方法?

        调用start()方法会启动一个新线程并检查其状态是否为“初始化”,在检查完毕后会将新线程加入到线程组中并调用start0()方法。直接调用run()方法相当于当前调用线程(主/子线程)调用了一个普通方法其并不会去做新建线程,加入线程组等这一系列操作;

3.如何正确停止线程

3.1.正确停止线程的原理

        使用interrupt来通知,而不是强制停止;(核心:想要停止线程其实是如何正确的用interrupt来通知那个需要被停止的线程,以及被停止的线程如何配合)

3.2.正确停止线程方法

情况一:run()方法内没有sleep()或wait()方法时停止线程

/**
 * 正确停止线程方法,run()方法内没有sleep()或wait()方法时停止线程
 */
public class RightWayStopThreadWithoutSleep implements Runnable{

    /**
     * 取Integer最大数的一半,取出是10000倍数的数字,且在线程执行1秒后停止线程
     */
    @Override
    public void run() {
        int num = 0;
        while (!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE/2){ // 每次循环时使用Thread.currentThread().isInterrupted()来监测当前线程是否需要被中断
            if(num % 10000 == 0){
                System.out.println(num + "是10000的倍数");
            }
            num ++;
        }
        System.out.println("程序执行完毕");
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadWithoutSleep());
               thread.start();
               Thread.sleep(1000);
               thread.interrupt(); // 使用interrupt()方法通知线程中断
    }
}

原理:

        主线程调用thread.interrupt()方法通知中断子线程,而子线程在每次的while循环中都会调用

Thread.currentThread().isInterrupted()方法来监测判断当前子线程是否需要被中断;

情况二:run()方法内带有sleep()等阻塞方法时中断线程写法

/**
 * 带有sleep()中断线程的写法
 */
public class RightWayStopThreadWithSleep implements Runnable {
    /**
     * 取300以内100倍数的数值(模拟当子线程进入5s休眠时,主线程发出中断信号,子线程会抛出“InterruptedException”异常。对这个异常在哪捕获(try{})决定了是否中断此线程(假如try中的代码包裹了“while循环”那么当“InterruptedException”异常
     * 抛出时则程序就会跳出while循环进而子线程中断))
     *      当子线程在休眠过程中收到了主线程的中断信号,子线程会响应主线程,只不过这个响应信息是抛出“InterruptedException”异常;对这个抛出的异常在哪捕捉决定了子线程是否中断(假如try包裹了子线程“循环体”当异常抛出时会导致跳出子线程循环体进而子线程中断)。
     */
    @Override
    public void run() {
        int num = 0;
        try {
            while(!Thread.currentThread().isInterrupted() && num <= 300){
                if(num % 100 == 0){
                    System.out.println(num + "是100的倍数");
                }
                num ++;
            }
            Thread.sleep(5000); // 休眠5s
        }catch (InterruptedException e){ // 当主线程发出中断通知时子线程收到通知并抛出“InterruptedException”异常,进而跳出while循环子线程中断。
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadWithSleep());
                thread.start();
                Thread.sleep(1000); // 主线程休眠1s确保子线程现在已进入5s的休眠时间
                thread.interrupt(); // 当子线程还在5s的休眠时间内,主线程使用interrupt()方法通知子线程中断
    }
}

原理:

        当子线程在休眠过程中收到了主线程的中断信号,子线程会响应主线程,只不过这个响应信息是抛出“InterruptedException”异常;对这个抛出的异常在哪捕捉决定了子线程是否中断(假如try包裹了子线程“循环体”当异常抛出时会导致跳出子线程循环体进而子线程中断)。

情况三:线程在每次循环后都会阻塞(sleep()或wait())时正确停止线程

/**
 * 如果在执行过程中,每次循环都会调用sleep()或wait()等阻塞方法时,那么就不需要在每次循环中使用Thread.currentThread().isInterrupted()来监测子线程是否需要中断。
 * 因为在sleep()或wait()等阻塞方法中会响应这个中断。
 */
public class RightWayStopThreadWithSleepEveryLoop implements Runnable {
    @Override
    public void run() {
        int num = 0;
        try {
            while(num <= 10000){
                if(num % 100 == 0){
                    System.out.println(num + "是100的倍数");
                }
                num ++;
                Thread.sleep(10); // 休眠10ms
            }
        }catch (InterruptedException e){ // 当主线程发出中断通知时子线程收到通知并抛出“InterruptedException”异常,进而跳出while循环子线程中断。
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadWithSleepEveryLoop());
        thread.start();
        Thread.sleep(5000); // 主线程休眠5s
        thread.interrupt();
    }
}

原理:

        如果在执行过程中,每次循环都会调用sleep()或wait()等阻塞方法时,那么就不需要在每次循环中使用Thread.currentThread().isInterrupted()来监测子线程是否需要中断。因为在sleep()或wait()等响应中断的阻塞方法中若收到“中断信号”sleep()或wait()会抛出InterruptedException异常来响应这个中断。

3.3.生产环境下中断线程的最佳实践

方式一:传递中断(优先选择)

        交给调用处处理中断异常;

/**
 * 生产中停止线程的最佳实践
 *      方式一:
 *      执行业务方法(throwInMethod中)选择在方法签名中抛出InterruptedException异常;那么在上游调用处run方法中就会强制要求try/cache去处理这个中断异常
 */
public class RightWayStopThreadInProd implements Runnable{

    @Override
    public void run() {
        while(true && !Thread.currentThread().isInterrupted()){
            System.out.println("开始执行业务");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                System.out.println("-> 收到中断信号正在做中断前的处理:保存数据&&记录日志");
                e.printStackTrace();
            }
        }
    }


    /**
     * 处理业务的方法
     *      若此方法收到中断信号则抛出InterruptedException异常,外抛的异常在run方法中被捕捉并做出相应中断线程前的处理(比如:保存数据/记录日志)
     */
    private void throwInMethod() throws InterruptedException {
        // 此处不要使用try/catch,因为此处使用try/catch会吞掉InterruptedException造成程序继续执行线程无法中断
        Thread.sleep(2000);
    }


    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd());
               thread.start();
               Thread.sleep(1000);
               thread.interrupt(); // 使用interrupt()方法通知线程中断
    }
}

方式二:恢复中断

/**
 * 生产中停止线程的最佳实践
 *      方式二:
 *      恢复中断,在业务方法中cache了中断异常(InterruptedException)使用Thread.currentThread().interrupt()重新恢复中断
 */
public class RightWayStopThreadInProd2 implements Runnable{

    @Override
    public void run() {
        while(true){
            if(Thread.currentThread().isInterrupted()){ // 业务方法中捕捉到中断后再恢复中断,在下次循环时被检查到进而结束线程
                System.out.println("-> 收到中断信号正在做中断前的处理:保存数据&&记录日志");
                break;
            }

            System.out.println("开始执行业务");
            throwInMethod();
        }
    }


    /**
     * 处理业务的方法
     *      若此方法收到中断信号则重新设置中断
     */
    private void throwInMethod(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            // 重新设置中断,等待run()方法中下次while循环时被检测
            Thread.currentThread().interrupt();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd2());
               thread.start();
               Thread.sleep(1000);
               thread.interrupt(); // 使用interrupt()方法通知线程中断
    }
}

Java响应中断的方法列表

        响应中断:即程序在执行下面这些方法时可以感知到中断信号,如果收到中断信号会响应中断。如sleep()方法当执行sleep方法时收到中断信号则线程会抛java.lang.InterruptedException: sleep interrupted异常来响应中断;

Object.wait()/wait(long)/wait(long,int);

Thread.sleep(long)/sleep(long,int);

Thread.join()/join(long)/join(long,int);

java.util.concurrent.BlockingQueue.take()/put(E);

java.util.concurrent.locks.Lock.lockInterruptibly();

java.util.concurrent.CountDownLatch.await();

java.util.concurrent.CyclicBarrier.await();

java.util.concurrent.Exchanger.exchange(V);

java.nio.channels.InterruptibleChannel的相关方法;

java.nio.channels.Selector的相关方法;

4.错误的停止线程方法

4.1.被弃用的stop/suspend/resume方法

           这些方法已被Java弃用,用stop()方法来停止线程会导致线程运行一半突然停止(调用stop方法线程会立即停止),没办法完成一个基本单位的操作(如一次循环为一个基本操作单位);suspend()和 resume()有死锁风险;

4.2.volatile设置boolean标记位

           此方式无法处理长时间阻塞的情况;

5.判断线程是否已被中断的相关方法

5.1.static boolean interrupted();

        该方法执行完后会清除中断信号,作用对象为当前调用此方法的线程,而并不是当前调用它的线程对象;

5.2.boolean isInterrupted();

        该方法执行完后不会清除中断信号(推荐);

5.3.Thread.interrupted();

        作用对象为当前调用此方法的线程,而并不是当前调用它的线程对象;

6.停止线程常见面试题

6.1.如何正确停止线程

       “请求方” 使用interrupt()方法来请求停止线程,interrupt()可以保证数据安全使用interrupt()来停止线程时线程并不会像stop()方法那样立马停止,当“被停止方”收到中断信号时线程何时停止是交给线程自己的,当使用interrupt()方法来停止线程时还需要在子方法中不断检测当前线程的“中断”状态;对于其它停止线程的方式比如已弃用的stop()方法会导致线程运行到一半突然终止可能会有数据安全问题且可能出现死锁,对于使用volatile设置boolean标记位的方式来停止线程不适用于长时间的阻塞情况;

6.2.如何处理“不可中断”的阻塞

什么是“不可中断阻塞”?

        比如执行IO操作时,即使调用interrupt()发出中断信号时其IO操作也不会被及时中断;没有具体的解决方法,针对特定的情况使用特定的方法,比如对于普通的IO操作我们可能没有办法及时响应,但是我们可以去使用那些可以响应中断的IO,去用那些可以响应中断的方法来响应中断;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值