Thread

本文介绍了两种优雅地停止线程的方法:使用布尔变量和Thread.interrupt()方法。使用Thread.interrupt()的优势在于能够立即从可中断的操作中退出,而使用标志位则需要等待操作完成才能检查标志。

run vs start

run()
If this thread was constructed using a separate Runnable run object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.
start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

如何优雅的停止一个线程?

  1. 使用 boolean volatile variable
  2. 使用Thread.Interrupt

Using Thread.interrupt() is a perfectly acceptable way of doing this. In fact, it’s probably preferrable to a flag as suggested above. The reason being that if you’re in an interruptable blocking call (like Thread.sleep or using java.nio Channel operations), you’ll actually be able to break out of those right away.

If you use a flag, you have to wait for the blocking operation to finish and then you can check your flag. In some cases you have to do this anyway, such as using standard InputStream/OutputStream which are not interruptable.

In that case, when a thread is interrupted, it will not interrupt the IO, however, you can easily do this routinely in your code (and you should do this at strategic points where you can safely stop and cleanup)

if (Thread.currentThread().isInterrupted()) {
  // cleanup and stop execution
  // for example a break in a loop
}

Like I said, the main advantage to Thread.interrupt() is that you can immediately break out of interruptable calls, which you can’t do with the flag approach.

Thread 类是 JVM 用于管理线程的类,每个线程都有一个 Thread 对象与之关联,JVM 会将这些 Thread 对象组织起来,用于线程调度和管理[^2]。 ### 功能与特性 Thread 对象具有 ID、名称、优先级、状态等属性,这些属性被 JVM 用于线程的调度和管理。在多线程环境下,根据多线程的内存原理,会开辟包含主线程的多个栈空间供 CPU 执行不同线程,不过线程执行的优先级通常由 CPU 决定,用户较难控制[^2][^3]。 ### 常见构造方法 - `Thread()`:创建一个线程对象。 - `Thread(Runnable target)`:使用 Runnable 对象创建线程对象。 - `Thread(String name)`:创建线程对象,并为其命名。 - `Thread(Runnable target, String name)`:使用 Runnable 对象创建线程对象,并为其命名[^2]。 ### 使用方法 #### 线程创建 - **继承 Thread 类,重写 run 方法** ```java class MyThread extends Thread { @Override public void run() { System.out.println("继承 Thread 类创建的线程在执行"); } } // 使用示例 MyThread thread = new MyThread(); thread.start(); ``` - **实现 Runnable 接口,重写 run 方法** ```java class MyRunnable implements Runnable { @Override public void run() { System.out.println("实现 Runnable 接口创建的线程在执行"); } } // 使用示例 Runnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); ``` - **继承 Thread 类,重写 run 方法,使用匿名内部类** ```java Thread thread = new Thread() { @Override public void run() { System.out.println("使用匿名内部类继承 Thread 类创建的线程在执行"); } }; thread.start(); ``` - **实现 Runnable 接口,重写 run 方法,使用匿名内部类** ```java Runnable runnable = new Runnable() { @Override public void run() { System.out.println("使用匿名内部类实现 Runnable 接口创建的线程在执行"); } }; Thread thread = new Thread(runnable); thread.start(); ``` - **使用 lambda 表达式(最推荐)** ```java Thread thread = new Thread(() -> { System.out.println("使用 lambda 表达式创建的线程在执行"); }); thread.start(); ``` #### 线程中断 - **使用标志位来控制线程是否要停止** ```java class MyThread extends Thread { private volatile boolean isStopped = false; @Override public void run() { while (!isStopped) { System.out.println("线程正在执行"); } System.out.println("线程已停止"); } public void stopThread() { isStopped = true; } } // 使用示例 MyThread thread = new MyThread(); thread.start(); thread.stopThread(); ``` - **使用 Thread 自带的标志位来控制线程是否要停止** ```java Thread thread = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { System.out.println("线程正在执行"); } System.out.println("线程已停止"); }); thread.start(); thread.interrupt(); ``` #### 线程等待 在 Java 中,可以使用 `join()` 方法让一个线程等待另一个线程执行完毕。例如: ```java Thread thread1 = new Thread(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程 1 执行完毕"); }); Thread thread2 = new Thread(() -> { try { thread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程 2 在等待线程 1 执行完毕后执行"); }); thread1.start(); thread2.start(); ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值