File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
src/main/java/com/example/concurrency/patterns/serialtask Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .example .concurrency .patterns .serialtask ;
2
+
3
+ import com .example .concurrency .features .threadPool .ThreadPoolBuilder ;
4
+ import com .example .concurrency .util .ThreadUtil ;
5
+
6
+ import java .util .concurrent .ThreadPoolExecutor ;
7
+ import java .util .concurrent .TimeUnit ;
8
+
9
+ /**
10
+ * 描述:
11
+ * 通过单锁和volatile 实现的线程共享方案
12
+ * 适用场景:特定条件下有效阻止并行执行
13
+ *
14
+ * @author zed
15
+ * @since 2019-07-02 3:33 PM
16
+ */
17
+ public class SerialTask {
18
+ /**
19
+ * 导出flag true:有任务在执行 false:可以执行当前任务
20
+ */
21
+ private static volatile boolean permits =false ;
22
+
23
+ /**
24
+ * 占用任务
25
+ */
26
+ public synchronized static boolean setPermits (){
27
+ if (!permits ){
28
+ permits = true ;
29
+ return true ;
30
+ }
31
+ return false ;
32
+ }
33
+ /**
34
+ * 释放任务
35
+ */
36
+ public synchronized static void releasePermits () {
37
+ permits = false ;
38
+ }
39
+ public static void main (String [] args ) throws InterruptedException {
40
+ ThreadPoolExecutor pool = ThreadPoolBuilder .cachedPool ().setThreadNamePrefix ("导出excel" ).build ();
41
+ for (int i =0 ;i < 10 ;i ++) {
42
+ pool .execute (() -> {
43
+ while (SerialTask .permits || !SerialTask .setPermits ()) {
44
+ //return or retry
45
+ }
46
+ SerialTask .setPermits ();
47
+ System .out .println (Thread .currentThread ().getName ()+"正在执行" );
48
+ ThreadUtil .sleep (1000 );
49
+ System .out .println (Thread .currentThread ().getName ()+"执行结束" );
50
+ SerialTask .releasePermits ();
51
+ });
52
+ }
53
+ pool .awaitTermination (5 , TimeUnit .SECONDS );
54
+
55
+ }
56
+ }
57
+
You can’t perform that action at this time.
0 commit comments