以前面试被虐的一道多线程题目
public class PrintABC {
Lock lock = new ReentrantLock(); //可重写锁
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
Condition conditionC = lock.newCondition();
public class printA implements Runnable {
@Override
public void run() {
for (int i = 0; i < 15; i++) {
lock.lock();
System.out.print("A");
conditionB.signal();
try {
conditionA.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
public class printB implements Runnable {
@Override
public void run() {
for (int i = 0; i < 15; i++) {
lock.lock();
System.out.print("B");
conditionC.signal();
try {
conditionB.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
public class printC implements Runnable {
@Override
public void run() {
for (int i = 0; i < 15; i++) {
lock.lock();
System.out.print("C");
conditionA.signal();
try {
conditionC.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
}
public static void main(String[] args) throws Exception {
PrintABC printABC = new PrintABC();
new Thread(printABC.new printA()).start();
new Thread(printABC.new printB()).start();
new Thread(printABC.new printC()).start();
return;
}
网友评论