线程可以通过调用线程对象的 interrupt() 方法来发送中断信号,从而中断线程。这意味着线程的中断是由其他线程调用 interrupt() 方法引起的。
Thread 类提供了三个中断方法:
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()<strong> </strong>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 started Main Thread finished [Thread-0] Message 0 This thread was interruped by someone calling this Thread.interrupt() Cancelling task running in thread Thread-0 After Thread.interrupted() call, JVM reset the interrupted value to: false
以上是如何在Java中中断正在运行的线程?的详细内容。更多信息请关注PHP中文网其他相关文章!