1
1
package com .examplehub .basics .thread ;
2
2
3
- import org .junit .jupiter .api .Test ;
4
-
5
3
import java .util .ArrayList ;
6
4
import java .util .LinkedList ;
7
5
import java .util .Queue ;
8
6
import java .util .concurrent .locks .Condition ;
9
7
import java .util .concurrent .locks .ReentrantLock ;
8
+ import org .junit .jupiter .api .Test ;
10
9
11
10
class ReentrantLockConditionExampleTest {
12
11
static class TaskQueue {
13
12
Queue <String > queue = new LinkedList <>();
14
13
ReentrantLock lock = new ReentrantLock ();
15
14
Condition condition = lock .newCondition ();
15
+
16
16
public void addTask (String task ) {
17
17
lock .lock ();
18
18
try {
19
19
queue .add (task );
20
20
condition .signalAll ();
21
- }finally {
21
+ } finally {
22
22
lock .unlock ();
23
23
}
24
24
}
@@ -30,47 +30,53 @@ public String getTask() throws InterruptedException {
30
30
condition .await ();
31
31
}
32
32
return queue .remove ();
33
- }finally {
34
- lock .unlock ();
33
+ } finally {
34
+ lock .unlock ();
35
35
}
36
36
}
37
37
}
38
+
38
39
@ Test
39
40
void test () throws InterruptedException {
40
41
var tasks = new TaskQueue ();
41
42
var threads = new ArrayList <Thread >();
42
43
for (int i = 0 ; i < 5 ; i ++) {
43
- Thread thread = new Thread (()->{
44
- while (true ) {
45
- try {
46
- String task = tasks .getTask ();
47
- System .out .println ("execute: " + task );
48
- } catch (InterruptedException e ) {
49
- System .out .println ("thread " + Thread .currentThread ().getName () + " interrupted" );
50
- return ;
51
- }
52
- }
53
- });
44
+ Thread thread =
45
+ new Thread (
46
+ () -> {
47
+ while (true ) {
48
+ try {
49
+ String task = tasks .getTask ();
50
+ System .out .println ("execute: " + task );
51
+ } catch (InterruptedException e ) {
52
+ System .out .println (
53
+ "thread " + Thread .currentThread ().getName () + " interrupted" );
54
+ return ;
55
+ }
56
+ }
57
+ });
54
58
thread .start ();
55
59
threads .add (thread );
56
60
}
57
- var addThread = new Thread (()->{
58
- for (int i = 0 ; i < 10 ; ++i ) {
59
- String task = "task - " + Math .random ();
60
- System .out .println ("added: " + task );
61
- tasks .addTask (task );
62
- try {
63
- Thread .sleep (100 );
64
- } catch (InterruptedException e ) {
65
- e .printStackTrace ();
66
- }
67
- }
68
- });
61
+ var addThread =
62
+ new Thread (
63
+ () -> {
64
+ for (int i = 0 ; i < 10 ; ++i ) {
65
+ String task = "task - " + Math .random ();
66
+ System .out .println ("added: " + task );
67
+ tasks .addTask (task );
68
+ try {
69
+ Thread .sleep (100 );
70
+ } catch (InterruptedException e ) {
71
+ e .printStackTrace ();
72
+ }
73
+ }
74
+ });
69
75
addThread .start ();
70
76
addThread .join ();
71
77
Thread .sleep (100 );
72
78
for (var thread : threads ) {
73
79
thread .interrupt ();
74
80
}
75
81
}
76
- }
82
+ }
0 commit comments