​ 一个线程不应该由其他线程来强制中断或停止,为了线程的健壮性,而是应该由线程自己自行停止,自己决定自己的命运。所以,Thread.stop,Thread.suspend,Thread.resume 都已经废弃了。

​ 在 Java 中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作。因此,Java 提供了一种用于停止线程的协商机制 ---- 中断,也即中断标识协商机制,并非强制。

​ 中断只是一种协商机制,Java 没有给中断增加任何语法,中断的过程完全需要程序员自己实现。若要中断一个线程,你需要手动调用该线程的 interrupt 方法,该方法也仅仅是将线程对象的中断标识设置成 true。

public void interrupt() {
  	if (this != Thread.currentThread())
    	checkAccess();
  	synchronized (blockerLock) {
    	Interruptible b = blocker;
    	if (b != null) {
      		// 具体还是底层的系统方法,给该线程的状态打上标识。
      		interrupt0();           // Just to set the interrupt flag
      		b.interrupt(this);
      		return;
    	}
  	}
  	interrupt0();
}

​ 接着你需要自己写代码不断地检测当前线程的标识位,如果为 true,表示别的线程请求这条线程中断。此时究竟该做什么需要你自己写代码实现。

​ 每个线程对象中都有一个中断标识位,用于表示线程是否被中断;该标识位为 true 表示中断,为 false 表示未中断;通过调用线程对象的 interrupt 方法将该线程的标识位设置为 true;可以在别的线程中调用,也可以在自己的线程中调用。

public static void main(String[] args) {
    new Thread(() -> {
        for (int i = 0; i < 18; i++) {
            if (i == 4) {
                Thread.currentThread().interrupt();
            }
            System.out.println(i);
            if (Thread.currentThread().isInterrupted()) {
                return;
            }
        }
    }).start();
}
// 子线程中循环打印 0 到 18,当循环到 4 时,在自己的线程中对自己发起中断,然后继续打印 4,然后检查是否存在中断,存在则直接返回结束。所以该 demo 只打印了 0,1,2,3,4

1、Thread 线程类中的 interrupt () 方法

实例方法:仅仅设置线程的中断状态为 true,发起一个协商而不会立刻停止线程。

public void interrupt() {
    if (this != Thread.currentThread())
        checkAccess();
    synchronized (blockerLock) {
        Interruptible b = blocker;
        if (b != null) {
            interrupt0();           // Just to set the interrupt flag
            b.interrupt(this);
            return;
        }
    }
    interrupt0();
}

2、Thread 线程类中的 interrupted () 方法

静态方法:判断线程是否被中断,并且清除当前的中断状态。isInterrupted (true)

第一:返回当前线程的中断状态,(测试当前线程是否被中断)。

第二:将当前线程的中断状态清零并重新设置为 false,(清除线程的中断状态)。

public static boolean interrupted() {
    return currentThread().isInterrupted(true);
}

3、Thread 线程类中的 isInterrupted () 方法

判断当前线程是否被中断(通过检查中断标识位,不会重置。)

public boolean isInterrupted() {
    return isInterrupted(false);
}

4、如何中断一个运行中的线程?

基本原理:通过一个线程可见性变量值的变化,来控制根据该变量值来控制执行逻辑的线程。

​ 方式 1:通过一个 volatile 变量实现,例如:A 线程想停止 B 线程,那么 A 线程需要持有 B 线程的信号变量(volatile),B 线程监控着该变量的的变化情况,做出响应,比如结束自己。

public class ThreadDemo {
    // 线程共享的信号变量,必须申明为 volatile 类型来保证线程见可见性,通过控制该变量的值,来控制别的线程的生命周期。
    private static volatile int info = 0;
    public static void main(String[] args) {
        new Thread(() -> {
            int i = 0;
            while (true) {
                System.out.println(Thread.currentThread().getName() + "===>>" + i++);
                if (ThreadDemo.info == 1) {
                    return;
                }
            }
        }, "Work").start();
        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }
        new Thread(() -> {
            ThreadDemo.info = 1;
        }, "Controller").start();
    }
}

​ 方式 2:通过原子类变量(类似方式 1)。

public class ThreadDemo {
    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    public static void main(String[] args) {
        new Thread(() -> {
            int i = 0;
            while (true) {
                System.out.println(Thread.currentThread().getName() + "===>>" + i++);
                if (ThreadDemo.atomicInteger.get() == 1) {
                    return;
                }
            }
        }, "Work").start();
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }
        new Thread(() -> {
            ThreadDemo.atomicInteger.set(1);
        }, "Controller").start();
    }
}

​ 方式 3、通过线程的中断标识协商机制。

public static void main(String[] args) {
    Thread t1 = new Thread(() -> {
        int i = 0;
      	//t1 线程根据线程的状态来判断逻辑
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println(Thread.currentThread().getName() + "===>>" + i++);
        }
    }, "Work");
    t1.start();
    try {
        TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException exception) {
        exception.printStackTrace();
    }
    // 外部线程对 t1 线程发起中断,即将 t1 线程的状态设置为 true.
    new Thread(t1::interrupt, "Controller").start(); 
}

5、如果停止一个运行中的线程?

通过上面一些方法,我们可以终止一些正常运行的线程,当某个线程中,调用了 wait,join 等方法会处于阻塞中,那么调用 interrupt 方法,那么线程会被唤醒,并且将线程的中断状态还原以及抛出异常。所以在线程中很可能出现死循环的等问题,无法结束线程操作,解决方案:实在捕获异常后,需要重新调用 interrupt 方法,因为 wait 方法接受中断信号号,会还原线程的中断状态。

Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an InterruptibleChannel then the channel will be closed, the thread’s interrupt status will be set, and the thread will receive a java.nio.channels.ClosedByInterruptException.
If this thread is blocked in a java.nio.channels.Selector then the thread’s interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector’s wakeup method were invoked.
If none of the previous conditions hold then this thread’s interrupt status will be set.

6、LockSupport

  • 除非许可证许可,否则禁用当前线程以进行线程调度。
public static void park() {
    UNSAFE.park(false, 0L);
}
  • 如果给定线程尚不可用,则为其提供许可。
public static void unpark(Thread thread) {
    if (thread != null)
        UNSAFE.unpark(thread);
}

7、3 种让线程等待和唤醒的方法。

方式 1、使用 Object 中的 wait () 方法让线程等待,使用 Object 中的 notify () 方法唤醒线程

public static void main(String[] args) {
    // 监视器
    Object lock = new Object();
    Thread t1 = new Thread(() -> {
        System.out.println(Thread.currentThread().getName() + ", start");
        synchronized (lock) {
            try {
                lock.wait(); // 必须获取锁后,才能调用此方法,当调用此方法后会释放锁。如果不先获取锁,就调用,则会报异常 java.lang.IllegalMonitorStateException
            } catch (InterruptedException exception) {
                exception.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + ", end");
    }, "t1");
    t1.start();
    try {
        TimeUnit.SECONDS.sleep(30L);
    } catch (InterruptedException exception) {
        exception.printStackTrace();
    }
    new Thread(() -> {
        synchronized (lock) {
            lock.notify();
        }
    }, "t2").start();
}

方式 2、使用 JUC 包中的 Condition 的 await () 方法让线程等待,使用 signal () 方法唤醒线程

Lock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
new Thread(() -> {
    System.out.println(Thread.currentThread().getName() + ", start");
    lock.lock();
    try {
        condition.await(); // 必须获取锁后,才能调用此方法,当调用此方法后会释放锁。如果不先获取锁,就调用,则会报异常 java.lang.IllegalMonitorStateException
        System.out.println(Thread.currentThread().getName() + ", end");
    } catch (InterruptedException ex) {
        ex.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        lock.unlock();
    }
}, "t1").start();
try {
    TimeUnit.SECONDS.sleep(10L);
} catch (InterruptedException exception) {
    exception.printStackTrace();
}
new Thread(() -> {
    System.out.println(Thread.currentThread().getName());
    lock.lock();
    try {
        condition.signal();
    } finally {
        lock.unlock();
    }
}, "t2").start();

方式 3、LockSupport 类可以阻塞当前线程以及唤醒指定被阻塞的线程。此方法采用许可证思想。

许可证 permit 默认没有不能放行,所以一开始调用 park 方法当前线程就会被阻塞,直到别的线程给当前线程发放 permit,park 方法才会被唤醒。重点:许可证不能累计

private static void type3() {
    final Thread t1 = new Thread(() -> {
        System.out.println(Thread.currentThread().getName() + ", start");
        LockSupport.park();
        System.out.println(Thread.currentThread().getName() + ", end");
    }, "t1");
    t1.start();
    try {
        TimeUnit.SECONDS.sleep(10L);
    } catch (InterruptedException exception) {
        exception.printStackTrace();
    }
    new Thread(() -> {
        System.out.println(Thread.currentThread().getName());
        LockSupport.unpark(t1);
    }, "t2").start();
}

这三种方式的进化过程:

第一种,缺点:1、wait,notify 方法必须要在同步块或者方法里面,且成对出现使用。

​ 2、先 wait,后 notify 才 OK,否则会出现线程永远阻塞。

第二种,解决了:第一种的那两个问题都没有解决

​ 缺点:1、await,signal 方法必须要在要先获取锁,且成对出现使用。

​ 2、先 await,后 signal 才 OK,否则会出现线程永远阻塞。

第三种,前两种缺点都解决了。

​ 无锁块,无顺序限制。

LockSupport 总结:

LockSupport 是用来创建锁和其他同步类的基本线程阻塞原语。

LockSupport 是一个线程阻塞工具类,所有的方法都是静态方法,可以让线程在任意位置阻塞,阻塞之后也有对应的唤醒方法。归根揭底,LockSupport 调用的 Unsafe 中的 native 代码。

LockSupport 提供了 park (),和 unpark () 方法实现阻塞线程和解除线程阻塞的过程。

LockSuport 和每个使用它的线程都有一个许可证(permit)关联。

每个线程都有一个相关的 permit,permit 最多只有一个,重复调用 unpark 也不会积累凭证。