1.线程中断
(1)通过thread 对象调用 interrupt 方法通知线程中断.
(2). thread 收到通知的方式有两种:
- 如果线程调用了 wait/join/sleep 等方法而阻塞挂起,则以 InterruptedException 异常的形式通知,清除中断标志
- 否则,只是内部的一个中断标志被设置,thread 可以通过
(设置中断标志:true; 清除中断标志:false)
①. Thread.interrupted() 判断当前线程的中断标志被设置,清除中断标志
② Thread.currentThread().isInterrupted() 判断指定线程的中断标志被设置,不清除中断标志
具体方法:
public void interrupt() :中断对象关联的线程,如果线程正在阻塞,则以异常方式通知,否则设置标志位
public static boolean interrupted() :判断当前线程的中断标志位是否设置,调用后清除标志位
public boolean isInterrupted(): 判断对象关联的线程的标志位是否设置,调用后不清除标志位
注意:调用interrupt() 方法,只是通知线程要终止, 至于线程是否终止,需要线程自行判断.
public static void main(String[] main) throws InterruptedException {
Thread t= new Thread( new Runnable() {
@Override
public void run() {
while (!Thread