代码拉取完成,页面将自动刷新
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();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。