线程可以通过调用线程对象的 interrupt() 方法来发送中断信号,从而中断线程。这意味着线程的中断是由其他线程调用 interrupt() 方法引起的。
thread 类提供了三个中断方法:
void interrupt() - 中断线程。static boolean interrupted() - 测试当前线程是否被中断。boolean isinterrupted() - 测试线程是否被中断。示例public class threadinterrupttest { public static void main(string[] args) { system.out.println("thread main started"); final task task = new task(); final thread thread = new thread(task); thread.start(); thread.interrupt(); // calling interrupt() method system.out.println("main thread finished"); }}class task implements runnable { @override public void run() { for (int i = 0; i < 5; i++) { system.out.println("[" + thread.currentthread().getname() + "] message " + i); if(thread.interrupted()) { system.out.println("this thread was interruped by someone calling this thread.interrupt()"); system.out.println("cancelling task running in thread " + thread.currentthread().getname()); system.out.println("after thread.interrupted() call, jvm reset the interrupted value to: " + thread.interrupted()); break; } } }}
输出thread main startedmain thread finished[thread-0] message 0this thread was interruped by someone calling this thread.interrupt()cancelling task running in thread thread-0after thread.interrupted() call, jvm reset the interrupted value to: false
以上就是如何在java中中断正在运行的线程?的详细内容。
