一、打断的三个方法
- boolean isInterrupted();
获取线程是否被打断
- void interrupt();
打断线程
- static boolean interrupted();
获取线程是否被打断,如果被打断,复位。
二、代码示例
1.3个方法使用示例:
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
System.out.println("初始状态:"+Thread.currentThread().isInterrupted());
while(true) {
if(Thread.currentThread().isInterrupted()) {
System.out.println("被打断状态:"+Thread.currentThread().isInterrupted());
// 复位
boolean interrupted = Thread.interrupted();
System.out.println("复位返回值:"+interrupted);
System.out.println("复位后状态:"+Thread.currentThread().isInterrupted());
}
}
});
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
t1.interrupt();
}
控制台输出:
初始状态:false
被打断状态:true
复位返回值:true
复位后状态:false
2.由实验得出的结论:当catch注InterruptedException,JVM会认为程序已经处理了打断,会自动复位打断状态。代码:
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
System.out.println("初始状态:"+Thread.currentThread().isInterrupted());
synchronized (WaitDemo.class) {
try {
WaitDemo.class.wait();
} catch (InterruptedException e) {
System.out.println("被打断状态:"+Thread.currentThread().isInterrupted());
// 复位
boolean interrupted = Thread.interrupted();
System.out.println("复位返回值:"+interrupted);
}
System.out.println("复位后状态:"+Thread.currentThread().isInterrupted());
}
});
t1.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
t1.interrupt();
}
控制台输出:
初始状态:false
被打断状态:false
复位返回值:false
复位后状态:false
三、什么方法被打断会抛出InterruptedException
- sleep()
- wait()
- join()
四、能否打断BLOCK状态
不可以,代码:
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
synchronized (args) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("被打断了");
}
}
});
t1.start();
Thread t2 = new Thread(() -> {
synchronized (args) {
}
System.out.println("输出t2");
});
t2.start();
Thread.sleep(1000);
t2.interrupt();
}
程序执行结果:5秒后才输出t2,证明t2没有被打断
五、能否打断Lock.lock()
lock()方法并不能被打断。与synchronized同理
但lockInterruptibly()方法可以被打断。
代码:
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
Thread t1 = new Thread(() -> {
lock.lock();
System.out.println("输出t1");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("t1被打断了");
}
lock.unlock();
});
t1.start();
Thread t2 = new Thread(() -> {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
System.out.println("t2被打断了");
}
System.out.println("输出t2");
});
t2.start();
Thread.sleep(2000);
t2.interrupt();
}