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