@@ -23,28 +23,9 @@ public void sort(int[] elements) {
23
23
Phaser phaser = new Phaser (numThreads );
24
24
Thread [] threads = new Thread [numThreads ];
25
25
for (int i = 0 ; i < numThreads ; i ++) {
26
- final int threadNo = i ;
27
- threads [threadNo ] =
28
- new Thread (
29
- () -> {
30
- int startPos = startPositions [threadNo ];
31
- int endPos = startPositions [threadNo + 1 ];
32
-
33
- for (int round = 1 ; ; round ++) {
34
- phaser .arriveAndAwaitAdvance ();
35
-
36
- boolean swapped = sortPartition (elements , startPos , endPos , false );
37
-
38
- phaser .arriveAndAwaitAdvance ();
39
-
40
- swapped |= sortPartition (elements , startPos , endPos , true );
41
- if (swapped ) lastSwappedInRound .set (round );
42
-
43
- phaser .arriveAndAwaitAdvance ();
44
-
45
- if (lastSwappedInRound .get () < round ) break ;
46
- }
47
- });
26
+ int startPos = startPositions [i ];
27
+ int endPos = startPositions [i + 1 ];
28
+ threads [i ] = createThread (elements , startPos , endPos , lastSwappedInRound , phaser );
48
29
}
49
30
50
31
for (int i = 0 ; i < numThreads ; i ++) {
@@ -85,6 +66,27 @@ private int[] partition(int[] elements) {
85
66
return startPositions ;
86
67
}
87
68
69
+ private Thread createThread (
70
+ int [] elements , int startPos , int endPos , AtomicInteger lastSwappedInRound , Phaser phaser ) {
71
+ return new Thread (
72
+ () -> {
73
+ for (int round = 1 ; ; round ++) {
74
+ phaser .arriveAndAwaitAdvance ();
75
+
76
+ boolean swapped = sortPartition (elements , startPos , endPos , false );
77
+
78
+ phaser .arriveAndAwaitAdvance ();
79
+
80
+ swapped |= sortPartition (elements , startPos , endPos , true );
81
+ if (swapped ) lastSwappedInRound .set (round );
82
+
83
+ phaser .arriveAndAwaitAdvance ();
84
+
85
+ if (lastSwappedInRound .get () < round ) break ;
86
+ }
87
+ });
88
+ }
89
+
88
90
/**
89
91
* Sorts a partition of the elements.
90
92
*
0 commit comments