CodeArena

线程顺序打印的几种方式

2023-08-23
最后更新:2024-05-23
2分钟
208字

1.使用 CountDownLatch

1
static CountDownLatch latch = new CountDownLatch(1);
2
3
public static void main(String[] args) throws InterruptedException {
4
Thread thread1 = new Thread(() -> {
5
System.out.println("A");
6
latch.countDown();
7
});
8
thread1.start();
9
latch.await();
10
11
latch = new CountDownLatch(1);
12
Thread thread2 = new Thread(() -> {
13
System.out.println("B");
14
latch.countDown();
15
});
11 collapsed lines
16
thread2.start();
17
latch.await();
18
19
latch = new CountDownLatch(1);
20
Thread thread3 = new Thread(() -> {
21
System.out.println("C");
22
latch.countDown();
23
});
24
thread3.start();
25
latch.await();
26
}

2.使用CyclicBarrier

1
static CyclicBarrier barrier = new CyclicBarrier(1);
2
3
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
4
Thread thread1 = new Thread(() -> {
5
System.out.println("A");
6
});
7
thread1.start();
8
barrier.await();
9
10
barrier.reset();
11
Thread thread2 = new Thread(() -> {
12
System.out.println("B");
13
});
14
thread2.start();
15
barrier.await();
8 collapsed lines
16
17
barrier.reset();
18
Thread thread3 = new Thread(() -> {
19
System.out.println("C");
20
});
21
thread3.start();
22
barrier.await();
23
}

3.使用Semphore

1
static Semaphore semaphore = new Semaphore(1);
2
3
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
4
semaphore.acquire();
5
Thread thread1 = new Thread(() -> {
6
System.out.println("A");
7
semaphore.release();
8
});
9
thread1.start();
10
11
semaphore.acquire();
12
Thread thread2 = new Thread(() -> {
13
System.out.println("B");
14
semaphore.release();
15
});
9 collapsed lines
16
thread2.start();
17
18
semaphore.acquire();
19
Thread thread3 = new Thread(() -> {
20
System.out.println("C");
21
semaphore.release();
22
});
23
thread3.start();
24
}

4.使用线程池

1
public static void main(String[] args) {
2
ExecutorService executorService = Executors.newSingleThreadExecutor();
3
4
for (int i = 0; i < 3; i++) {
5
int finalI = i;
6
executorService.submit(() -> {
7
System.out.println((char)('A' + finalI));
8
});
9
}
10
}
本文标题:线程顺序打印的几种方式
文章作者:Echoidf
发布时间:2023-08-23
感谢大佬送来的咖啡☕
alipayQRCode
wechatQRCode