1
+ package com .codecafe .concurrency .semaphore ;
2
+
3
+ import java .text .DateFormat ;
4
+ import java .text .SimpleDateFormat ;
5
+ import java .util .Date ;
6
+ import java .util .concurrent .*;
7
+
8
+ // Throttle task submission
9
+ public class TaskLimitSemaphore {
10
+
11
+ private final ExecutorService executor ;
12
+ private final Semaphore semaphore ;
13
+
14
+ public TaskLimitSemaphore (ExecutorService executor , int limit ) {
15
+ this .executor = executor ;
16
+ this .semaphore = new Semaphore (limit );
17
+ }
18
+
19
+ public <T > Future <T > submit (final Callable <T > task ) throws InterruptedException {
20
+
21
+ semaphore .acquire ();
22
+ System .out .println ("semaphore.acquire()..." );
23
+
24
+ return executor .submit (() -> {
25
+ try {
26
+ return task .call ();
27
+ } finally {
28
+ semaphore .release ();
29
+ System .out .println ("semaphore.release()..." );
30
+ }
31
+ });
32
+
33
+ }
34
+
35
+ private static final DateFormat sdf = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss" );
36
+
37
+ public static void main (String [] args ) throws InterruptedException {
38
+
39
+ ExecutorService executor = Executors .newCachedThreadPool ();
40
+
41
+ // only support 2 tasks
42
+ TaskLimitSemaphore obj = new TaskLimitSemaphore (executor , 2 );
43
+
44
+ obj .submit (() -> {
45
+ System .out .println (getCurrentDateTime () + " : task1 is running!" );
46
+ Thread .sleep (2000 );
47
+ System .out .println (getCurrentDateTime () + " : task1 is done!" );
48
+ return 1 ;
49
+ });
50
+
51
+ obj .submit (() -> {
52
+ System .out .println (getCurrentDateTime () + " : task2 is running!" );
53
+ Thread .sleep (2000 );
54
+ System .out .println (getCurrentDateTime () + " task2 is done!" );
55
+ return 2 ;
56
+ });
57
+
58
+ obj .submit (() -> {
59
+ System .out .println (getCurrentDateTime () + " task3 is running!" );
60
+ Thread .sleep (2000 );
61
+ System .out .println (getCurrentDateTime () + " task3 is done!" );
62
+ return 3 ;
63
+ });
64
+
65
+ obj .submit (() -> {
66
+ System .out .println (getCurrentDateTime () + " task4 is running!" );
67
+ Thread .sleep (2000 );
68
+ System .out .println (getCurrentDateTime () + " task4 is done!" );
69
+ return 4 ;
70
+ });
71
+
72
+ obj .submit (() -> {
73
+ System .out .println (getCurrentDateTime () + " task5 is running!" );
74
+ Thread .sleep (2000 );
75
+ System .out .println (getCurrentDateTime () + " task5 is done!" );
76
+ return 5 ;
77
+ });
78
+
79
+ executor .shutdown ();
80
+ }
81
+
82
+ private static String getCurrentDateTime () {
83
+ return sdf .format (new Date ());
84
+ }
85
+ }
0 commit comments