多线程循环打印ABC
方法一:
package org.example;
import java.util.TreeMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class PrintABC {
ReentrantLock lock = new ReentrantLock();
Condition a = lock.newCondition();
Condition b = lock.newCondition();
Condition c = lock.newCondition();
char ch = 'A';
public void printA() {
lock.lock();
try {
while (ch != 'A') {
try {
a.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("A");
ch = 'B';
b.signal();
} finally {
lock.unlock();
}
}
public void printB() {
lock.lock();
try {
while (ch != 'B') {
try {
b.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("B");
ch = 'C';
c.signal();
} finally {
lock.unlock();
}
}
public void printC() {
lock.lock();
try {
while (ch != 'C') {
try {
c.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("C");
ch = 'A';
a.signal();
} finally {
lock.unlock();
}
}
}
public class TestPrintABC {
public static void main(String[] args) {
PrintABC printABC = new PrintABC();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
printABC.printA();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
printABC.printB();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
printABC.printC();
}
}
}).start();
}
}
标签:ch,Java,lock,void,try,面试,经典,new,public
From: https://www.cnblogs.com/DCFV/p/18292598