Java多线程--三个线程分别打印a,b,c.请用多线程实现循环打印15次abc

Java多线程–三个线程分别打印a,b,c.请用多线程实现循环打印15次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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* Created by CHG on 2017-02-23 20:20.
*/
public class PrintABC {
int count = 0; //打印次数
Lock lock = new ReentrantLock(); //可重写锁
Condition conditionA = this.lock.newCondition();
Condition conditionB = this.lock.newCondition();
Condition conditionC = this.lock.newCondition();

public class PrintA implements Runnable {
@Override
public void run() {
while (true)
if (count < 15) {
lock.lock();
System.out.print("A");
try {
conditionB.signal(); //线程b唤醒,因为a打印完应该打印b
conditionA.await(); //线程a进入等待队列
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}

}
}
}

public class PrintB implements Runnable {
@Override
public void run() {
while (true)
if (count < 15) {
lock.lock();
System.out.print("B");
try {
conditionC.signal();
conditionB.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}

}
}
}

public class PrintC implements Runnable {
@Override
public void run() {
while (true)
if (count < 15) {
lock.lock();
System.out.println("C" + count);
count++;//打印完c后,count++
try {
conditionA.signal();
conditionC.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}

}
}
}

public static void main(String[] args) {
PrintABC printABCD = new PrintABC();
new Thread(printABCD.new PrintA()).start();
new Thread(printABCD.new PrintB()).start();
new Thread(printABCD.new PrintC()).start();

}

}
今天最好的表现,是明天最低的要求。