java 礼物打赏并发
时间: 2023-11-24 13:51:04 浏览: 42
Java 礼物打赏并发可以通过多线程实现。具体实现方式如下:
1.定义礼物打赏任务类 GiftTask,实现 Runnable 接口,重写 run() 方法,在方法中实现礼物打赏的逻辑。
2.定义礼物打赏线程池类 GiftThreadPool,使用 Executors.newFixedThreadPool() 方法创建一个固定大小的线程池,将礼物打赏任务 GiftTask 提交到线程池中执行。
3.在主函数中,创建礼物打赏线程池对象 GiftThreadPool,调用 execute() 方法提交礼物打赏任务 GiftTask 到线程池中执行。
以下是示例代码:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class GiftTask implements Runnable {
private String giftName;
private int giftNum;
public GiftTask(String giftName, int giftNum) {
this.giftName = giftName;
this.giftNum = giftNum;
}
@Override
public void run() {
// 礼物打赏逻辑
System.out.println(Thread.currentThread().getName() + " 打赏了 " + giftNum + " 个 " + giftName);
}
}
public class GiftThreadPool {
private ExecutorService executorService;
public GiftThreadPool(int nThreads) {
executorService = Executors.newFixedThreadPool(nThreads);
}
public void execute(GiftTask giftTask) {
executorService.execute(giftTask);
}
}
public class Main {
public static void main(String[] args) {
GiftThreadPool giftThreadPool = new GiftThreadPool(10);
for (int i = 0; i < 100; i++) {
GiftTask giftTask = new GiftTask("礼物" + i, i);
giftThreadPool.execute(giftTask);
}
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)