java interrupt

本文通过一个简单的Java示例介绍了线程中断的概念及其工作原理。当一个线程被中断时,并不会立即停止运行,而是由程序员决定如何响应中断请求。示例展示了即使线程被中断后,仍然可能继续运行的情况。

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

See following tutorial from sun:

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. This is the usage emphasized in this lesson.

So if a thread is interrupted, it maybe continue to run without stop. Whether it will stop is up to the programmer.

See the example below: ( I copied from http://hapinwater.iteye.com/blog/310558)

class ATask implements Runnable{   
  
    private double d = 0.0;   
       
    public void run() {   
        //死循环执行打印"I am running!" 和做消耗时间的浮点计算   
        while (true) {   
            System.out.println("I am running!");   
               
            for (int i = 0; i < 900000; i++) {   
                d =  d + (Math.PI + Math.E) / d;   
            }   
            //给线程调度器可以切换到其它进程的信号   
            Thread.yield();   
        }   
    }   
}   
  
public class InterruptTaskTest {   
       
    public static void main(String[] args) throws Exception{   
        //将任务交给一个线程执行   
        Thread t = new Thread(new ATask());   
        t.start();   
           
        //运行一断时间中断线程   
        Thread.sleep(100);   
        System.out.println("****************************");   
        System.out.println("Interrupted Thread!");   
        System.out.println("****************************");   
        t.interrupt();   
    }   
}   

 
The result shows:

......   
I am running!   
I am running!   
I am running!   
I am running!   
****************************   
Interrupted Thread!   
****************************   
I am running!   
I am running!   
I am running!   
I am running!   
I am running!   
....  

 

Check here for more information about interrupt in java:

http://hapinwater.iteye.com/blog/310558 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值