Java实现线程的方式和线程中断方式有哪些?

Java实现线程的方式和线程中断方式有哪些?

一般是使用以下的三种方式实现线程:
  • 实现Runnable接口
  • 实现Callable接口
  • 继承Thread类
    实现Runnable和Callable接口的类只能当做一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过Thread来调用。可以说任务是通过线程驱动而执行的
接着我我们了解一下线程中断的方式:
  • 一般情况下,一个线程执行完毕后会自动结束,如果在运行过程中发生异常也会提前结束
  • InterruptedException
    通过调用一个线程的interrupt()来中断该线程,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就睡抛出InterruptedException,从而提前结束该线程,但是不能中断I/O阻塞和synchronized锁阻塞
    对于以下代码,在main()中启动一个线程之后再中断,由于线程中调用了Thread.sleep()方法,因此会抛出一个InterruptedException异常,从而会提前结束该线程,不执行以后的语句
    public class InterruptExample {
        private static class MyThread extends Thread{
            public void run(){
                try {
                    Thread.sleep(2000);
                    System.out.println("Thread run");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    
        public static void main(String[] args) {
            Thread thread=new MyThread();
            thread.start();
            thread.interrupt();
            System.out.println("Main run");
        }
    }
    
    java.lang.InterruptedException: sleep interrupted
    	at java.lang.Thread.sleep(Native Method)
    	at oop.thread.InterruptExample$MyThread.run(InterruptExample.java:11)
    
  • Interruped()
    如果一个线程的run()方法执行一个无限循环,并没有执行sleep()等会抛出InterruptedException的操作,那么调用线程的interrupt()方法就无法使线程结束
    但是调用interrupt()方法会设置线程的中断标记,此时调用interrupt() 方法会返回true。因此可以在循环中使用interrupted() 方法来判断线程是否处于中断状态,从而提前结束线程
  • Executor的中断操作
    调用Executor的shutdown()方法会等待线程都执行完毕之后再关闭,但是如果调用的是shutdownNow() 方法,则相当于调用每个线程的interrupt() 方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值