-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestSemaphore.java
More file actions
45 lines (32 loc) · 1.26 KB
/
TestSemaphore.java
File metadata and controls
45 lines (32 loc) · 1.26 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
package com.test.multithread.semaphore;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class TestSemaphore {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Semaphore semaphore = new Semaphore(1);
ExecutorService service = Executors.newFixedThreadPool(5);
//IntStream.of(10000).forEach(i -> service.execute(new Task(semaphore)));
for(int i = 0; i < 10; i++) {
service.execute(new Task(semaphore));
}
service.shutdown();
service.awaitTermination(1, TimeUnit.MINUTES);
}
static class Task implements Runnable{
Semaphore semaphore;
public Task(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
semaphore.tryAcquire();
System.out.println(Thread.currentThread().getName() + " is running");
semaphore.release();
System.out.println(Thread.currentThread().getName() + " Hello");
}
}
}