代码的运行结果和的不一样为什么 lock.lockInterruptibly(); 没用,打断线程0的时
来源:5-4 获取锁时被中断
心中有个梦
2020-04-13
下面代码中和视视频的一样,为什么在打断线程0 的时候,线程1在线程0还没有释放锁的时候就获取到了锁,

package lock.lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*
*/
public class LockInterruptibly implements Runnable{
private Lock lock = new ReentrantLock();
public static void main(String[] args) {
Thread thread0 = new Thread(new LockInterruptibly());
Thread thread1 = new Thread(new LockInterruptibly());
thread0.start();
thread1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread0.interrupt();
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"尝试获取锁");
try {
lock.lockInterruptibly();
try{
System.out.println(Thread.currentThread().getName()+"获取到了锁");
Thread.sleep(5000);
}catch (InterruptedException e){
System.out.println(Thread.currentThread().getName() + "睡眠期间被中断了!");
}finally {
lock.unlock();
System.out.println(Thread.currentThread().getName()+"释放了锁");
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "获得锁时候被中断了!");
}
}
}
写回答
1回答
-
你的代码和我的不一样,需要new LockInterruptibly()是同一个实例
142020-04-13
相似问题