一个线程如何中断Java中的另一个线程?
可以在Java中使用“中断”功能,借助InterruptedException异常来中断线程的执行。
以下示例显示了当前正在执行的线程一旦被中断,如何停止执行(由于catch块中引发了新的异常)-
示例
public class Demo extends Thread
{
public void run() {
try
{
Thread.sleep(150);
System.out.println("In the 'run' function inside try block");
}
catch (InterruptedException e)
{
throw new RuntimeException("The thread has been interrupted");
}
}
public static void main(String args[])
{
Demo my_inst = new Demo();
System.out.println("An instance of the Demo class has been created");
my_inst.start();
try
{
my_inst.interrupt();
}
catch (Exception e)
{
System.out.println("The exception has been handled");
}
}
}输出结果
An instance of the Demo class has been created Exception in thread "Thread-0" java.lang.RuntimeException: The thread has been interrupted at Demo.run(Demo.java:12)
名为Demo的类扩展了Thread类。在“try”块中,定义了一个名为“run”的函数,该函数使该函数休眠150毫秒。在“捕获”块中,捕获了异常,并且在控制台上显示了相关消息。
在main函数中,创建了Demo类的实例,并使用“start”函数启动了线程。在“try”块中,实例被中断,在“catch”块中,显示指示异常的相关消息。