lockInterruptibly是中断获取锁的操作,可以让线程去干别的事情
代码部分
package com.java.test.lock; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @Description: * @Author: Yourheart * @Create: 2023/1/28 16:29 */ @Slf4j @RestController public class LockDemo { private Lock lock = new ReentrantLock(); @RequestMapping("/lockInterruptiblyThreadOne") public String lockInterruptiblyThreadOne() throws InterruptedException { LockDemo lockDemo=new LockDemo(); Thread t0 = new Thread( new Runnable() { @Override public void run() { lockDemo.doBussiness(); } } ); // 启动线程t0 t0.start(); Thread.sleep(10); return "启动线程t1"; } @RequestMapping("/lockInterruptiblyThreadTwo") public String lockInterruptiblyThreadTwo() throws InterruptedException { LockDemo lockDemo=new LockDemo(); Thread t1 = new Thread( new Runnable() { @Override public void run() { lockDemo.doBussiness(); dealWith(); } } ); // 启动线程t1 t1.start(); Thread.sleep(100); // 线程t1没有得到锁,中断t1的等待 t1.interrupt(); return "启动线程t1"; } public void doBussiness() { String name = Thread.currentThread().getName(); try { log.info(name + " 开始获取锁"); lock.lockInterruptibly(); log.info(name + " 得到锁"); log.info(name + " 开工干活"); for (int i = 0; i < 10; i++) { Thread.sleep(2000); log.info(name + " : " + i); } } catch (InterruptedException e) { log.info(name + " 被中断"); log.info(name + " 做些别的事情"); } finally { try { lock.unlock(); log.info(name + " 释放锁"); } catch (Exception e) { log.info(name + " : 没有得到锁的线程运行结束"); } } } public void dealWith(){ log.info("中断获取锁的操作后,开始做的事情....."); } }
我是采用接口的方式测试的
两个接口地址 127.0.0.1:2001/lockInterruptiblyThreadOne 127.0.0.1:2001/lockInterruptiblyThreadTwo
标签:info,log,Thread,lockInterruptibly,使用,t1,线程,简单,name From: https://www.cnblogs.com/q202105271618/p/17070802.html