可打断
import java.util.concurrent.locks.ReentrantLock;
/*
ReentrantLock可打断
**/
public class T {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + " 尝试获得锁");
lock.lockInterruptibly();
System.out.println(Thread.currentThread().getName() + " 线程获得了锁");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getName() + " 线程没有获得锁,被打断...catch{return}");
} finally {
lock.unlock();
System.out.println(Thread.currentThread().getName() + " 释放锁");
}
}, "线程1");
System.out.println(Thread.currentThread().getName() + " 获得锁");
//main线程加锁原因:为了使线程1一直处于运行状态(此处即一直在获取main持有的锁)。
//假如main线程不加锁:线程1套层while(true)一直处于运行状态,再打断即可。
lock.lock();
thread.start();
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "...");
//打断线程1
thread.interrupt();
System.out.println(Thread.currentThread().getName() + " 释放锁");
lock.unlock();
}
}
标签:Thread,currentThread,getName,ReentrantLock,System,线程,out
From: https://www.cnblogs.com/goodluckxiaotuanzi/p/18360313