提交 | 用户 | 时间
|
149dd0
|
1 |
package com.iailab.netsdk.common; |
H |
2 |
import java.util.concurrent.ExecutorService; |
|
3 |
import java.util.concurrent.Executors; |
|
4 |
import java.util.concurrent.Future; |
|
5 |
import java.util.concurrent.LinkedBlockingDeque; |
|
6 |
|
|
7 |
public class EventTaskCommonQueue { |
|
8 |
|
|
9 |
// 设置一个队列,容量看情况改 |
|
10 |
private final int MAX_TASK_COUNT = 10000; // 队列容量 |
|
11 |
private final LinkedBlockingDeque<EventTaskHandler> eventTasks = new LinkedBlockingDeque<EventTaskHandler>(MAX_TASK_COUNT); |
|
12 |
|
|
13 |
// 起一个线程池 |
|
14 |
private final int MAX_THREAD_COUNT = 10; // 线程池容量 |
|
15 |
private ExecutorService eventQueueService = Executors.newFixedThreadPool(MAX_THREAD_COUNT); |
|
16 |
|
|
17 |
// 用于检验服务运行状态 |
|
18 |
private volatile boolean running = true; |
|
19 |
|
|
20 |
// 用于查看当前线程状态 |
|
21 |
private Future<?> eventQueueThreadStatus; |
|
22 |
|
|
23 |
// 初始化 |
|
24 |
public void init() { |
|
25 |
eventQueueThreadStatus = eventQueueService.submit(new Thread(new Runnable() { |
|
26 |
@Override |
|
27 |
public void run() { |
|
28 |
while (running) { |
|
29 |
try { |
|
30 |
EventTaskHandler task = eventTasks.take(); //开始一个任务 |
|
31 |
try { |
|
32 |
task.eventTaskProcess(); // 主要的运行函数 |
|
33 |
} catch (Exception e) { |
|
34 |
System.err.println("任务处理发生错误"); // error |
|
35 |
} |
|
36 |
} catch (InterruptedException e) { |
|
37 |
System.err.println("任务已意外停止"); // error |
|
38 |
running = false; |
|
39 |
} |
|
40 |
} |
|
41 |
} |
|
42 |
}, "Event call back thread init")); |
|
43 |
} |
|
44 |
|
|
45 |
// 向队列添加新的任务 |
|
46 |
public boolean addEvent(EventTaskHandler eventHandler) { |
|
47 |
if (!running) { |
|
48 |
System.out.println("任务已停止"); // warning |
|
49 |
return false; |
|
50 |
} |
|
51 |
boolean success = eventTasks.offer(eventHandler); |
|
52 |
if (!success) { |
|
53 |
// 队列已满,无法再添加 |
|
54 |
System.out.println("添加到事件队列失败"); |
|
55 |
} |
|
56 |
return success; |
|
57 |
} |
|
58 |
|
|
59 |
|
|
60 |
// 手动启动服务 |
|
61 |
public void activeService() { |
|
62 |
running = true; |
|
63 |
if (eventQueueService.isShutdown()) { |
|
64 |
eventQueueService = Executors.newFixedThreadPool(MAX_THREAD_COUNT);; |
|
65 |
init(); |
|
66 |
System.out.println("线程池已关闭,重新初始化线程池及任务"); |
|
67 |
} |
|
68 |
if (eventQueueThreadStatus.isDone()) { |
|
69 |
init(); |
|
70 |
System.out.println("线程池任务结束,重新初始化任务"); |
|
71 |
} |
|
72 |
} |
|
73 |
|
|
74 |
// 手动关闭服务 |
|
75 |
public void destroy() { |
|
76 |
running = false; |
|
77 |
eventQueueService.shutdownNow(); |
|
78 |
} |
|
79 |
} |