使用java写使用线程池并100个异步线程抢一把锁
时间: 2023-07-04 10:11:02 浏览: 194
要使用Java写使用线程池并100个异步线程抢一把锁,可以结合上面提到的线程池和锁的示例代码,将它们结合起来。下面是一个示例代码:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadPoolWithLockDemo {
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
// 创建线程池对象,使用FixedThreadPool类型
ExecutorService executor = Executors.newFixedThreadPool(5);
// 提交任务
for (int i = 0; i < 100; i++) {
executor.execute(new Task(i));
}
// 关闭线程池
executor.shutdown();
}
static class Task implements Runnable {
private int id;
public Task(int id) {
this.id = id;
}
@Override
public void run() {
lock.lock();
try {
System.out.println("Task " + id + " get the lock on thread " + Thread.currentThread().getName());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
System.out.println("Task " + id + " release the lock on thread " + Thread.currentThread().getName());
}
}
}
}
```
在这个示例代码中,创建了一个FixedThreadPool类型的线程池,最多可以有5个线程同时执行任务。提交了100个任务,每个任务都是一个Runnable接口的实现类。任务执行时,会首先尝试获取锁,如果获取到了,则打印一条获取锁的信息,并且睡眠1秒钟模拟线程执行的过程。当线程执行结束时,会释放锁,并且打印一条释放锁的信息。最后,调用了线程池的shutdown()方法来关闭线程池。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)