线程的启动与停止

线程的启动只有start()方法;
中断线程仅仅 只是优雅的打个招呼,改变一个状态位 具体怎么做完全取决于线程自己,让程序有时间去完成一些未完成的事情,释放资源等, 温柔以待。

1、线程的启动

记得以前学习线程的时候有几个疑惑,记录一下,先看一个例子:
public class RunnableThreadTest implements Runnable {
   
    @Override
    public void run() {
        System.out.println("Runnable thread test");
    }

    public static void main(String[] args) {
        //实例化线程任务类
        RunnableThreadTest task = new RunnableThreadTest();
        Thread thread =  new Thread(task);  // 语句1
        task.run();                         // 语句2
        thread.start();                     // 语句3
    }
}

思考1:语句1: Thread thread = new Thread();此时创建线程了吗?

思考2: task.run()创建线程了吗?
启动一个线程 为什么是调用start方法,而不是run方法,这里做一个简单的分析.
public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();


    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);


    boolean started = false;
    try {
        start0();  //这里调用了本地方法start0()方法去启动一个线程
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

查看jdk的源码我们看到调用 start 方法实际上是调用一个 native 方法 start0()。这里在调用thread.start()的时候,其实调用了jvm中native中c语言方法,基于底层os去创建启动一个线程,因为java线程的实现模型是 一个用户线程对应一个内核线程 “1:1模型”,然后再回掉thread的run()方法,写死的,所以需要创建一个线程就调用start(),最终是由操作系统来完成的,具体步骤:

  • 先构造一个javaThread .start()
  • 然后再调用native thread是 start0() 调用不同的操作系统 os:createThread()去创建线程;
  • 最后,调用thread的start(),再回掉 run()方法,启动任务的执行;
注意: 语句2 如果直接去调用run()并没有启动一个线程,只是一个本地方法的调用;语句1只是创建了一个任务类实例对象;我们需要的是启动一个线程,所以需要语句3 start();

2、关闭线程

    线程的终止,并不是简单的调用stop命令。stop方法在结束一个线程时并不会保证线程的资源正常释放,因此会导致程序可能出现一些不确定的状态,例如数据的一致性问题。 所以在线程中提供了一个interrupt方法,可以优雅的去中断停止一个线程,具体什么时候停止由线程自己决定。
先来看一个线程运行中断的实例:
//中断方式一:通过检测中断位触发中断逻辑,调用中断interrupted,设置interrupt的标识位为true;
public static void main(String[] args) throws InterruptedException {

    Thread thread1 = new Thread(() -> {
        int i = 0;
        System.out.println("before interrupt: " + Thread.currentThread().isInterrupted());
        //检测中断标示位,只有中断后设置interrupt的标识位为true;才会跳出这个循环
        while (!Thread.currentThread().isInterrupted()) { 
            i++;
            if ((i % 1000) == 0)
                System.out.println(i);
        }
        System.out.println("after interrupt: " + Thread.currentThread().isInterrupted());

    }, "interrupt-thread");

    thread1.start();
    TimeUnit.MILLISECONDS.sleep(1);
    thread1.interrupt();  //中断线程thread1;
}
运行结果:
before interrupt: false
1000
2000
3000
after interrupt: true

从上面可以看出:interrupt()对正在执行的线程thread1进行了中断;这样我们就可以更好的控制线程的运行,线程退出运行的时机,而不是暴力的停止。

线程池中线程的关闭
线程池中线程的关闭通过自己 实现的AQS互斥锁中断机制保证不会立即停止一个正在执行的线程,但是也提供了两种方式:
  • 方式一:线程的状态为 SHUTDOWN,拒绝接受新任务 + 执行完队列里的任务;
  • 方式二:线程的状态为 SHUTDOWNNOW,立即中断正在执行的线程,队列里的任务不会执行,容易引起数据的一致性问题;
推荐方式一优雅的实现关闭线程:shutdown(): 

3、中断的理解

Thread.interrupt ()并不是中断线程,而是告诉线程一声,该中断了, 至于什么时候中断,取决于当前线程自己 ,这个很合理, a 线程本身在执行什么,执行到什么地方,这些 b 线程都不知道,你怎么能说终止就终止呢?所以线程的终止应该由线程自己本身来决定。
中断类型
运行中断:如果一个线程处于 Running 状态,通过 interrupt()来将中断位设置为true,仅此而已。程序的运行不受影响,具体怎么做需要线程本身来决定,开篇就是一个与行时中断的实例。
阻塞中断:当一个线程处于 wait () /sleep () /join 等状态的时候,通过唤醒后抛出interuptedException异常停止一个阻塞的线程,给了一个停止线程的入口,程序的执行不受影响,仅此而已。

3.1、中断响应

    中断响应就是 通过 interrupt() 设置一个状态的值state,让线程通过isInterrupted()返回值去判断该值的状态,然后根据状态去做响应处理;也可以使用 interrupted()去复位中断。通过interrupt()源码可以看出,终止一个线程,仅仅是设置一个中断位的标志而已。
public void interrupt() {
    if (this != Thread.currentThread())
        checkAccess();

    synchronized (blockerLock) {
        Interruptible b = blocker;
        if (b != null) {
            interrupt0();           // Just to set the interrupt flag — 仅仅只是去设置一个标志位状态而已;
            b.interrupt(this);
            return;
        }
    }
    interrupt0();
}

从源码可以看出,interrupt0()是一个本地native方法,调用了底层不同操作系统的interrupt()方法来设置中断标志位interrupted的值为true,并且通过ParkEvent的unpark方法来唤醒线程,对于 synchronized 阻塞的线程,被唤醒以后会继续尝试获取锁,如果失败仍然可能被park。

Stop(), 还是interrupt(), isinterrupted(),  interrupted(),深入理解这些方法?
首先一个线程不应该由其他线程来强制中断或者停止,而是应该由线程自己停止,所以,Thread.stop()暴力法已经废弃了。
interrupte() 主要做两件事
  1. 设置共享变量interrupted()为true, 线程是否停止取决于之后线程自己;
  2. 如果阻塞则unpark()当前的线程;
isInterrupted() 判断线程是否中断;
interrupted() 线程中断标示复位;
  • 通过interrupt()设置了一个标识告诉线程可以终止了,所以线程中也提供了静态方法Thread.interrupted()对设置中断标识的线程进行复位。
  • 主要作用是:让其他线程知道了我接收到了中断信号;在中断之前我的状态仍然是false;

3.2、InterruptedException复位中断

    除了通过 Thread.interrupted 方法对线程中断标识进行复位以外,还有一种被动复位的场景,就是对抛出InterruptedException异常的方法,在InterruptedException抛出之前,JVM 会先把线程的中断标识位清除,然后才会抛出InterruptedException,这个时候如果调用isInterrupted方法,将会返回false。下面看一个阻塞中断实例:
//中断方式二:超时阻塞,允许一个线程来请求自己中断当前的操作。
//调用sleep()/wait()/join()/park()阻塞时, 调用interrupt()通过抛异常来中断处于阻塞中的线程
public static void main(String[] args) throws InterruptedException {

    Thread thread2 = new Thread(() -> {
        int i = 0;
        while (true) {
            try {
                i++;
                TimeUnit.MILLISECONDS.sleep(10); //睡眠阻塞10ms;
                if ((i % 100) == 0)
                    System.out.println("i:  " + i);
            } catch (InterruptedException e) { //注意:jvm在抛出异常前会复位中断位,如果这里什么都不做,那么此中断对程序的执行没有任何影响;
                System.out.println("收到中断,抛出异常:");
                //todo 线程去做一些收尾的工作,然后释放一些资源,继续向上抛异常,最后退出,也可以什么都不做;
                e.printStackTrace();
            }
        }
    }, "interrupt-thread2");

    thread2.start();
    TimeUnit.MILLISECONDS.sleep(1000);
    thread2.interrupt();//打扰中断thread2的休眠,thread2会抛出一个异常然后继续执行;
}

运行结果:

注意:从结果可以看到,虽然收到了异常但是线程并没有停止,而是一直在继续运行,这就是因为在抛出异常之前线程将中断位复位为false了,如果程序在接受异常后什么都不做,那么程序将一直运行下去。

4、问题思考

思考一:为什么要复位?
    Thread.interrupted()是属于当前线程的,是当前线程对外 界中断信号的一个响应,表示自己已经得到了中断信号,但不会立刻中断自己,具体什么时候中断由自己决定,让外界知道在自身中断前,他的中断状态仍然是false,这就是复位的原因
思考二: 写代码的时候会发现,为什么Object.wait()、Thread.sleep()和Thread.join()都会抛出InterruptedException?
    首先这些方法都属于阻塞的方法 而阻塞方法的释放会取决于一些外部的事件,但是阻塞方法可能因为等不到外部的触发事件而导致无法终止,所以它允许一个线程请求自己来停止它正在做的事情。当一个方法抛出InterruptedException时,它是在告诉调用者如果执行该方法的线程被中断,它会尝试停止正在做的事情 并且通过抛出InterruptedException表示提前返回。
所以,这个异常的意思是表示一个阻塞被其他线程中断了。然后,由于线程调用了interrupt()中断方法,那么Object.wait、Thread.sleep等被阻塞的线程被唤醒以后会通过isInterrupted()方法判断中断标识的状态变化,如果发现中断标识为true,则先清除中断标识,然后抛出InterruptedException。
    需要注意的是,InterruptedException异常的抛出并不意味着线程必须终止,而是提醒当前线程有中断的操作发生,至于接下来怎么处理取决于线程本身,比如:
  • 1. 直接捕获异常不做任何处理;
  • 2. 将异常往外抛出;
  • 3. 停止当前线程,并打印异常信息;

5、小结

    停止一个线程最好的方式是中断,中断只是将中断标志位设置为true,其他什么都不做,线程具体怎么处理取决于线程自己,从而可以更好的控制线程的运行,防止数据一致性和安全性。
 
 
水滴石穿,积少成多。学习笔记,内容简单,用于复习,梳理巩固。
 
 

 

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中可以通过`threading`模块来启动停止线程。具体的方法如下: 启动线程: 1. 定义一个线程类,继承自`threading.Thread`类,重写`run()`方法,在`run()`方法中写入线程要执行的代码。 2. 创建线程实例对象,并调用`start()`方法启动线程,此时线程会自动调用`run()`方法执行。 示例代码: ```python import threading # 自定义线程类 class MyThread(threading.Thread): def run(self): # 线程要执行的代码 print("Thread started") # 创建线程实例对象 t = MyThread() # 启动线程 t.start() ``` 停止线程: 1. 在线程中定义一个变量作为标志位,用于控制线程的运行状态。 2. 在线程中使用循环语句,根据标志位的状态来决定是否退出循环,从而终止线程的运行。 示例代码: ```python import threading import time # 自定义线程类 class MyThread(threading.Thread): def __init__(self): super().__init__() self.flag = True def run(self): # 线程要执行的代码 while self.flag: print("Thread is running...") time.sleep(1) print("Thread stopped") def stop(self): self.flag = False # 创建线程实例对象 t = MyThread() # 启动线程 t.start() # 停止线程 t.stop() ``` 注意:线程停止并不能直接调用`stop()`方法来实现,因为这样会导致线程的资源没有被释放,从而引发各种问题。正确的做法是在线程中定义一个标志位,通过修改标志位的状态来控制线程的运行状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值