暂停线程

本文详细介绍了Java中线程中断机制的实现原理与使用方法,包括如何通过interrupt()方法中断线程,以及如何利用interrupted()和isInterrupted()方法来检查线程是否已被中断。同时,还探讨了sleep方法在遇到线程中断时的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一下推荐的方法暂停线程。

package thread;

public class MyThread extends Thread {
    @Override
    public void run() {
    //  super.run();
        try {
            for (int i = 0; i < 500000; i++) {
                if (this.interrupted()) {//一直检查有没有被打断
                    System.out.println("已经是停止状态了!我要退出了!");
                    throw new InterruptedException();
                }
                System.out.println("i=" + (i + 1));
            }
            System.out.println("我在for下面");
        } catch (InterruptedException e) {
            System.out.println("进MyThread.java类run方法中的catch了!");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(2000);
            thread.interrupt();//这里置了标志位
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

这就是中断异常法

  1. interrupt()
    interrupt方法用于中断线程。调用该方法的线程的状态为将被置为”中断”状态。
    注意:线程中断仅仅是置线程的中断状态位,不会停止线程。需要用户自己去监视线程的状态为并做处理。支持线程中断的方法(也就是线程中断后会抛出interruptedException的方法)就是在监视线程的中断状态,一旦线程的中断状态被置为“中断状态”,就会抛出中断异常。
  2. interrupted() 和 isInterrupted()
    首先看一下API中该方法的实现:
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
private native boolean isInterrupted(boolean ClearInterrupted);

因此这两个方法有两个主要区别:
interrupted 是作用于当前线程,isInterrupted 是作用于调用该方法的线程对象所对应的线程。(线程对象对应的线程不一定是当前运行的线程。例如我们可以在A线程中去调用B线程对象的isInterrupted方法,而interrupted则是只能判断当前线程有没有被打断)
sleep方法的描述

void java.lang.Thread.sleep(long millis) throws InterruptedException
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

Parameters:
millis the length of time to sleep in milliseconds
Throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

大概意思是会让线程暂停执行指定的时间,并且不会释放调锁。
而且如果受到线程的打断,他会抛出异常并且置标志位。

### 如何在 VB.NET 中暂停线程 为了实现线程暂停功能,在 VB.NET 中可以利用 `System.Threading` 命名空间下的类来管理多线程操作[^4]。然而,直接提供暂停方法并不是 .NET Framework 的一部分;通常的做法是通过设置标志位让目标线程进入等待状态从而达到暂停的效果。 下面是一个简单的例子展示如何模拟暂停行为: ```vb.net Imports System.Threading Module Module1 Private stopWatch As Stopwatch = New Stopwatch() Private pauseFlag As Boolean = False Private exitFlag As Boolean = False Sub Main() Dim workerThread As Thread = New Thread(AddressOf WorkerMethod) workerThread.Start() Console.WriteLine("Press P to Pause/Resume or Q to Quit.") While Not exitFlag Select Case Console.ReadKey(True).KeyChar.ToString.ToUpper Case "P" pauseFlag = Not pauseFlag If pauseFlag Then Console.WriteLine("Paused...") Else Console.WriteLine("Resumed...") End If Case "Q" exitFlag = True Console.WriteLine("Quitting...") End Select Thread.Sleep(100) ' Reduce CPU usage. End While workerThread.Join() ' Wait for the thread to finish. End Sub Private Sub WorkerMethod() Do Until exitFlag If Not pauseFlag Then Console.WriteLine($"Working at {stopWatch.ElapsedMilliseconds} ms") stopWatch.Restart() Thread.Sleep(500) ' Simulate some work being done. Else stopWatch.Stop() Thread.Sleep(100) ' Avoid busy waiting when paused. End If Loop End Sub End Module ``` 此代码展示了创建并控制一个工作线程的方式,该线程可以根据用户的输入被挂起或恢复运行。当按下键 “P” 时会切换线程的状态(即暂停与否),而按“Q”则退出程序。 值得注意的是,上述方式并非真正的暂停机制而是基于轮询的一种解决方案。对于更复杂的场景可能需要考虑其他同步原语如 `Monitor.Wait()` 和 `Monitor.Pulse()` 来协调多个线程之间的交互[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值