-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoolExample.java
More file actions
50 lines (43 loc) · 2.12 KB
/
PoolExample.java
File metadata and controls
50 lines (43 loc) · 2.12 KB
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
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class PoolExample {
public static void main(String[] args) throws InterruptedException {
// создаем пул для выполнения наших задач
// максимальное количество созданных задач - 3
ThreadPoolExecutor executor = new ThreadPoolExecutor(
// не изменяйте эти параметры
3, 3, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3));
// сколько задач выполнилось
AtomicInteger count = new AtomicInteger(0);
// сколько задач выполняется
AtomicInteger inProgress = new AtomicInteger(0);
// отправляем задачи на выполнение
for (int i = 0; i < 30; i++) {
final int number = i;
Thread.sleep(10);
System.out.println("creating #" + number);
executor.setRejectedExecutionHandler((runnable, exec) -> System.out.println("rejected"));
while (executor.getActiveCount() >= 3)
{
//wait
}
executor.submit(() -> {
int working = inProgress.incrementAndGet();
System.out.println("start #" + number + ", in progress: " + working);
try {
// тут какая-то полезная работа
Thread.sleep(Math.round(1000 + Math.random() * 2000));
} catch (InterruptedException e) {
// ignore
}
working = inProgress.decrementAndGet();
System.out.println("end #" + number + ", in progress: " + working + ", done tasks: " + count.incrementAndGet());
return null;
});
}
executor.shutdown();
}
}