多线程交替打印

多线程交替打印

打印0~100

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
46
47
public class multiThreadedPrinting {

private static volatile int count = 0;
private static final int MAX = 100;
private static final Object LOCK = new Object();

public static void main(String[] args) {
Thread thread1 = new Thread(new Seq(0));
Thread thread2 = new Thread(new Seq(1));
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}

static class Seq implements Runnable {
private final int index;

public Seq(int index) {
this.index = index;
}

@Override
public void run() {
while(count < MAX) {
synchronized (LOCK) {
// 判断当前线程能不能打印?
while (count % 2 != index) {
try {
LOCK.wait();
} catch (Exception e) {
e.printStackTrace();
}
}

if(count > MAX) {
LOCK.notify();
return;
}
System.out.println("Thread " + index + ": " + count);
count++;
LOCK.notify();
}
}
}
}
}

打印 ABC

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
public class multiThreadedPrinting3 {
private static final int count = 3;
private static final Semaphore semA = new Semaphore(1);
private static final Semaphore semB = new Semaphore(0);
private static final Semaphore semC = new Semaphore(0);

public static void main(String[] args) {
new Thread(new Task("A", semA, semB)).start();
new Thread(new Task("B", semB, semC)).start();
new Thread(new Task("C", semC, semA)).start();
}

private static class Task implements Runnable {
private final String value;
private final Semaphore current;
private final Semaphore next;

public Task(String value, Semaphore current, Semaphore next) {
this.value = value;
this.current = current;
this.next = next;
}

@Override
public void run() {
for(int i = 0; i < count; i ++) {
try {
current.acquire();
System.out.println(value);
next.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

多线程交替打印
https://sowink.cn/2026/04/12/多线程交替打印/
作者
Xurx
发布于
2026年4月12日
许可协议