0%

1114-按序打印

前言:学习JUC包后,通过leetcode多线程的题目练习一下,1114-按序打印

自旋

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
public class Foo {
private AtomicInteger flag = new AtomicInteger(1);

public Foo() {
}

public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
flag.getAndIncrement();
}

public void second(Runnable printSecond) throws InterruptedException {
for (;;) {
if (flag.intValue() == 2) {
break;
}
}
printSecond.run();
flag.getAndIncrement();
}

public void third(Runnable printThird) throws InterruptedException {
for (;;) {
if (flag.intValue() == 3) {
break;
}
}
printThird.run();
}
}

Semaphore

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Foo {
private Semaphore[] semaphores = new Semaphore[2];
public Foo() {
semaphores[0] = new Semaphore(0);
semaphores[1] = new Semaphore(0);
}

public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
semaphores[0].release();
}

public void second(Runnable printSecond) throws InterruptedException {
semaphores[0].acquire();
printSecond.run();
semaphores[1].release();
}

public void third(Runnable printThird) throws InterruptedException {
semaphores[1].acquire();
printThird.run();
}
}

CountDownLatch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Foo {
private CountDownLatch one = new CountDownLatch(1);
private CountDownLatch two = new CountDownLatch(1);
public Foo() {

}

public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
one.countDown();
}

public void second(Runnable printSecond) throws InterruptedException {
one.await();
printSecond.run();
two.countDown();
}

public void third(Runnable printThird) throws InterruptedException {
two.await();
printThird.run();
}
}

CyclicBarrier

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
public class Foo {
private CyclicBarrier[] cyclicBarriers = new CyclicBarrier[2];
public Foo() {
cyclicBarriers[0] = new CyclicBarrier(2);
cyclicBarriers[1] = new CyclicBarrier(3);
}

public void first(Runnable printFirst) throws InterruptedException {
printFirst.run();
try {
cyclicBarriers[0].await();
cyclicBarriers[1].await();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}

public void second(Runnable printSecond) throws InterruptedException {
try {
cyclicBarriers[0].await();
printSecond.run();
cyclicBarriers[1].await();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}


}

public void third(Runnable printThird) throws InterruptedException {
try {
cyclicBarriers[1].await();
printThird.run();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
-------------本文结束感谢您的阅读-------------