multithreading-print

多线程打印宝典

典中典多线程打印题,我来归纳一下:

  1. 三个线程分别打印 A,B,C,要求这三个线程一起运行,打印 n 次,输出形如“ABCABCABC….”的字符串

使用Semaphore

这一招也是我最喜欢的,简单无脑

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
public class Main {
private static final Semaphore[] s = {new Semaphore(1), new Semaphore(0), new Semaphore(0)};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.close();
new Thread(() -> {
try {
for (int i = 0; i < n; i++) {
s[0].acquire();
System.out.print('A');
s[1].release();
}

} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
for (int i = 0; i < n; i++) {
s[1].acquire();
System.out.print('B');
s[2].release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
for (int i = 0; i < n; i++) {
s[2].acquire();
System.out.print('C');
s[0].release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}

使用ReentrantLock

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
public class Main {
private final int times;
private int status;
private static final Lock lock = new ReentrantLock();
private static final Condition c1 = lock.newCondition();
private static final Condition c2 = lock.newCondition();
private static final Condition c3 = lock.newCondition();

public Main(int times) {
this.times = times;
}

public static void main(String[] args) {
Main main = new Main(10);
new Thread(() -> {
main.printLetter(0, c1, c2);
}, "A").start();
new Thread(() -> {
main.printLetter(1, c2, c3);
}, "B").start();
new Thread(() -> {
main.printLetter(2, c3, c1);
}, "C").start();
}

public void printLetter(int targetStatus, Condition current, Condition next) {
for (int i = 0; i < times; ) {
lock.lock();
try {
while (status % 3 != targetStatus) {
current.await();
}
++status;
++i;
System.out.print(Thread.currentThread().getName());
next.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}

使用Lock/Condition的话虽说代码比Semaphore复杂,但是可以做到精准控制,比如,AA 打印 5 次,BB 打印10 次,CC 打印 15 次,重复 10 次

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
public class Main {
private int status;
private static final Lock lock = new ReentrantLock();
private static final Condition c1 = lock.newCondition();
private static final Condition c2 = lock.newCondition();
private static final Condition c3 = lock.newCondition();

public static void main(String[] args) {
Main main = new Main();
new Thread(() -> {
for (int i = 0; i < 5; i++)
main.printLetter(0, c1, c2, 5);
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 5; i++)
main.printLetter(1, c2, c3, 10);
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
main.printLetter(2, c3, c1, 15);
System.out.print(" | ");
}
}, "C").start();
}

public void printLetter(int targetStatus, Condition current, Condition next, int times) {
lock.lock();
try {
while (status % 3 != targetStatus) {
current.await();
}
for (int i = 0; i < times; i++) {
System.out.print(Thread.currentThread().getName());
}
++status;
next.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}

gsxxbQ.png

使用 LockSupport

LockSupport 是 JDK 底层的基于 sun.misc.Unsafe 来实现的类,用来创建锁和其他同步工具类的基本线程阻塞原语。它的静态方法unpark()park()可以分别实现阻塞当前线程和唤醒指定线程的效果,所以用它解决这样的问题会更容易一些。

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
public class Main {
private static final Thread[] threads = new Thread[3];
public static void main(String[] args) {
threads[0] = new Thread(() -> {
for (int i = 0; i < 50; i++) {
System.out.print(Thread.currentThread().getName());
LockSupport.unpark(threads[1]);
LockSupport.park();
}
}, "A");
threads[1] = new Thread(() -> {
for (int i = 0; i < 50; i++) {
LockSupport.park();
System.out.print(Thread.currentThread().getName());
LockSupport.unpark(threads[2]);
}
}, "B");
threads[2] = new Thread(() -> {
for (int i = 0; i < 50; i++) {
LockSupport.park();
System.out.print(Thread.currentThread().getName());
LockSupport.unpark(threads[0]);
}
}, "C");
for (Thread t : threads) {
t.start();
}
}
}

这种方法与Semaphore有异曲同工之妙,也是十分简单的一种方式!

  1. 交替打印奇偶数字
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
public class Main {
private int status;
private static final Lock lock = new ReentrantLock();
private static final Condition c1 = lock.newCondition();
private static final Condition c2 = lock.newCondition();

public static void main(String[] args) {
Main main = new Main();
new Thread(() -> {
main.printNum(100, 0, c1, c2);
}, "even:").start();
new Thread(() -> {
main.printNum(100, 1, c2, c1);
}, "odd:").start();
}

public void printNum(int times, int targetStatus, Condition current, Condition next) {
while (status < times) {
lock.lock();
try {
while (status % 2 != targetStatus) {
current.await();
}
System.out.print(Thread.currentThread().getName() + status + " ");
++status;
next.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}

gy90R1.png

使用LockSupport一如既往的简单易懂。

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 Main {
private static final Thread[] threads = new Thread[2];
public static void main(String[] args) {
threads[0] = new Thread(() -> {
// 注意上下的循环steps一定要是一样的,否则程序不会运行结束
for (int i = 0; i < 100; i += 2) {
System.out.print(Thread.currentThread().getName() + i + " ");
LockSupport.unpark(threads[1]);
LockSupport.park();
}
}, "even:");
threads[1] = new Thread(() -> {
for (int i = 1; i <= 100; i += 2) {
LockSupport.park();
System.out.print(Thread.currentThread().getName() + i + " ");
LockSupport.unpark(threads[0]);
}
}, "odd:");
for (Thread t : threads) {
t.start();
}
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!