现在的位置: 首页 > 编程语言 > 正文

Java中断一个线程操作示例

2020年02月13日 编程语言 ⁄ 共 1356字 ⁄ 字号 评论关闭

本文实例讲述了Java中断一个线程操作。分享给大家供大家参考,具体如下:

一 点睛

中断一个线程,意味着该线程在完成任务之前,停止它正在进行的一切当前的操作。

有三个比较常用的函数:

interrupt():一个正在运行的A线程,可以调用B线程对应的interrupt方法来中断线程B。这个方法的核心功能是,将线程B的中断标识位属性设置为true。

isInterrupted():通过该方法判断某个线程是否处于中断状态。

interrupted():这是一个静态方法,用来获取当前线程的中断状态,并清除中断状态。获取的是清除之前的值,也就是说连续两次调用此方法,第二次一定会返回false。

二 代码

public class SleepInterrupt implements Runnable{ public void run() { try { System.out.println( "在run()方法中 ——这个线程休眠10秒" ); Thread.sleep( 10000 ); System.out.println( "在run()方法中 —— 继续运行" ); } catch( InterruptedException x ) { System.out.println( "在run()方法中 - 中断线程" ); return; } System.out.println( "在run()方法中 - 休眠之后继续完成" ); System.out.println( "在run()方法中 - 正常退出" ); } public static void main( String[] args ) { SleepInterrupt si = new SleepInterrupt(); Thread newThd = new Thread( si ); newThd.start(); // 在此休眠是为确保线程能运行一会 try { System.out.println( "在main()方法中——休眠2秒!" ); Thread.sleep( 2000 ); } catch( InterruptedException e ) { e.printStackTrace(); } System.out.println( "在main()方法中——中断newThd 线程" ); newThd .interrupt(); System.out.println( "在main()方法中 ——退出" ); }}

三 运行

在main()方法中——休眠2秒!在run()方法中 ——这个线程休眠10秒在main()方法中——中断newThd 线程在run()方法中 - 中断线程在main()方法中 ——退出

四 说明

interrupt()方法并不会使正在执行的线程停止执行,它只对wait、join、sleep等方法或由于I/O操作等原因受阻的线程产生影响,使其退出暂停执行的状态。

它对正在运行的线程不起作用。

更多java相关内容感兴趣的读者可查看本站专题:《Java进程与线程操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

本文标题: Java中断一个线程操作示例

以上就上有关Java中断一个线程操作示例的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.