Java线程中断(interrupt)与阻塞(park)的区别 很多Java开发⼈员(包括我),尤其是刚进⼊软件⾏业的新⼿,认为Java设置线程中断就是表⽰线程停⽌了,不往前执⾏了,
Thread.currentThread().interrupt()
其实不是这样的,线程中断只是⼀个状态⽽已,true表⽰已中断,fal表⽰未中断
//获取线程中断状态,如果中断了返回true,否则返回fal
Thread.currentThread().isInterrupted()
设置线程中断不影响线程的继续执⾏,但是线程设置中断后,线程内调⽤了wait、jion、sleep⽅法中的⼀种, ⽴马抛出⼀个InterruptedException,且中断标志被清除,重新设置为fal。
class Thread2 implements Runnable{
@Override
public void run() {
try {
System.out.println();
System.out.println(hread.currentThread().isInterrupted());//输出fal
Thread.currentThread().interrupt();//当前线程中断
System.out.println("Thread.currentThread().isInterrupted());//输出true
Thread.sleep(3000);//中断后执⾏sleep会抛出异常
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Thread.currentThread().isInterrupted());//输出fal
}
}
}
该如何让线程真正停⽌不往前执⾏呢:
真正让线程停⽌下来(阻塞),Java提供了⼀个较为底层的并发⼯具类:LockSupport,该类常⽤的⽅法有两个,1
park(Object blocker) 表⽰阻塞指定线程,参数blocker当前线程对象 2 unpark(Thread thread) 唤醒指定线程,参数thread指定线程对象
⽰例:
public void test_LockSupport(){
Thread thread=new Thread(new Thread_park());
thread.start();//阻塞当前线程
Thread thread2=new Thread(new Thread_unpark(thread)); thread2.start();//唤醒被阻塞的线程
}
class Thread_park implements Runnable{
@Override
public void run() {
System.out.println("Thread_park开始");
LockSupport.park(this);//阻塞当前线程
System.out.println("Thread_park结束");
}
}
class Thread_unpark implements Runnable{
private Thread thread;
public Thread_unpark(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
System.out.println("Thread_unpark开始");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LockSupport.unpark(thread);//唤醒被阻塞的线程
System.out.println("Thread_unpark结束");
}
}