1 Star 0 Fork 0

Neo_1001/LeetCode刷题记录

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
InterruptibleLockExample.java 1.99 KB
一键复制 编辑 原始数据 按行查看 历史
Neo_1001 提交于 2024-04-10 22:16 . first commit
package LeetCode;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class InterruptibleLockExample {
public void performTask(ReentrantLock lock) {
try {
// 尝试获取锁,可以中断
lock.lockInterruptibly();
System.out.println("performTask 获得锁");
try {
// 在这里执行任务
System.out.println("performTask 任务执行中...");
Thread.sleep(3000); // 模拟任务执行时间
System.out.println("performTask 任务执行结束...");
} finally {
// 释放锁
System.out.println("performTask 释放锁");
lock.unlock();
}
} catch (InterruptedException e) {
// 线程被中断
System.out.println("线程被中断,放弃执行任务");
}
}
public static void main(String[] args) throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
InterruptibleLockExample example = new InterruptibleLockExample();
Thread taskThread = new Thread(() -> {
example.performTask(lock);
});
// lock.lock();
// System.out.println("主线程获得锁");
//
// taskThread.start();
//
// Thread.sleep(3000);
//
// System.out.println("performTask 中断获取锁的过程");
// taskThread.interrupt();
//
// System.out.println("主线程释放锁");
// lock.unlock();
ThreadPoolExecutor executor = new ThreadPoolExecutor(4,
8,
1,
TimeUnit.HOURS,
new LinkedBlockingQueue<Runnable>());
executor.submit(taskThread);
executor.shutdown();
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/neo1001/leet-code-practice-record.git
git@gitee.com:neo1001/leet-code-practice-record.git
neo1001
leet-code-practice-record
LeetCode刷题记录
master

搜索帮助