
线程可以通过调用线程对象的 interrupt() 方法来发送中断信号,从而中断线程。这意味着线程的中断是由其他线程调用 interrupt() 方法引起的。
Thread 类提供了三个中断方法:
睿拓智能网站系统-网上商城1.0免费版软件大小:5M运行环境:asp+access本版本是永州睿拓信息专为电子商务入门级用户开发的网上电子商城系统,拥有产品发布,新闻发布,在线下单等全部功能,并且正式商用用户可在线提供多个模板更换,可实现一般网店交易所有功能,是中小企业和个人开展个人独立电子商务商城最佳的选择,以下为详细功能介绍:1.最新产品-提供最新产品发布管理修改,和最新产品订单查看2.推荐产
- 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 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










