Java并发编程笔记之基础总结(二)

一.线程中断 Java 中线程中断是一种线程间协做模式,经过设置线程的中断标志并不能直接终止该线程的执行,而是须要被中断的线程根据中断状态自行处理。   1.void interrupt() 方法:中断线程,例如当线程 A 运行时,线程 B 能够调用线程 A 的 interrupt() 方法来设置线程 A 的中断标志为 true 并当即返回。设置标志仅仅是设置标志,线程 A 并无实际被中断,会继续往下执行的。若是线程 A 由于调用了 wait 系列函数或者 join 方法或者 sleep 函数而被阻塞挂起,这时候线程 B 调用了线程 A 的 interrupt() 方法,线程 A 会在调用这些方法的地方抛出 InterruptedException 异常而返回。   2.boolean isInterrupted():检测当前线程是否被中断,若是是返回 true,否者返回 false,代码以下: public boolean isInterrupted() { //传递false,说明不清除中断标志 return isInterrupted(false); }      3.boolean interrupted():检测当前线程是否被中断,若是是返回 true,否者返回 false,与 isInterrupted 不一样的是该方法若是发现当前线程被中断后会清除中断标志,而且该函数是 static 方法,能够经过 Thread 类直接调用。另外从下面代码能够知道 interrupted() 内部是获取当前调用线程的中断标志而不是调用 interrupted() 方法的实例对象的中断标志。 public static boolean interrupted() { //清除中断标志 return currentThread().isInterrupted(true); } 下面看一个线程使用 Interrupted 优雅退出的经典使用例子,代码以下: public void run(){ try{ .... //线程退出条件 while(!Thread.currentThread().isInterrupted()&& more work to do){ // do more work; } }catch(InterruptedException e){ // thread was interrupted during sleep or wait } finally{ // cleanup, if required } }
相关文章
相关标签/搜索