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
package problem;

import java.util.concurrent.locks.ReentrantLock;

/**
* @Autor HumgTop
* @Date 2021/5/26 9:35
* @Version 1.0
* 3个线程顺序打印数字 1-100
*/
public class ShunXuDaYin1_100DeZhi {
static int num = 0;
static ReentrantLock lock = new ReentrantLock();

public static void main(String[] args) {
new MyThread(0).start();
new MyThread(1).start();
new MyThread(2).start();
}

static class MyThread extends Thread {
int tag; //线程标记号,用于顺序同步

public MyThread(int tag) {
this.tag = tag;
}

@Override
public void run() {
while (num < 100) {
//双重检查锁定:避免其他线程在num<100时进入while循环,然后阻塞。等到取到锁时,num已经大于100。如果不作二次检查,会导致打印出大于100的值。
lock.lock();
//取模运算保证线程打印的顺序
if (num < 100 && num % 3 == tag) {
System.out.print(Thread.currentThread());
num++;
System.out.print(num + "\n");
}
lock.unlock();
}
}
}
}