JAVA实现,3个线程交替A,B,C,一共完成10次“ABC”打印,结束后打印“END”。
打印示例:
abc abc abc abc abc abc abc abc abc abc END
分析:
打印10次ABC,3个线程分别打印A,B,C字符,打印完唤醒下一个线程,需要使用锁在子线程间精确唤醒控制,synchronized + 3个对象锁,或ReentrantLock+3个Condition,效果一样。
打印结束时打印END,如果由主线程打印,则可以用CountDownLatch进行主、子线程同步控制。
示例代码:
import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class PrintABC extends Thread { private static ReentrantLock lock = new ReentrantLock(); private static int count = 10; private static CountDownLatch cdl = new CountDownLatch(3); private Condition cur; private Condition next; private char ch; public PrintABC(Condition cur, Condition next, char ch) { this.cur = cur; this.next = next; this.ch = ch; } @Override public void run() { lock.lock(); try { for (int i = 1; i <= count; ++i) { System.out.print(ch); if (ch == 'c') { System.out.println(); } next.signal(); if (i < count) { try { cur.await(); } catch (Exception e) { //ignore } } } } finally { lock.unlock(); } cdl.countDown(); } public static void main(String[] args) throws Exception { Condition a = lock.newCondition(); Condition b = lock.newCondition(); Condition c = lock.newCondition(); new PrintABC(a, b, 'a').start(); new PrintABC(b, c, 'b').start(); new PrintABC(c, a, 'c').start(); cdl.await(); System.out.println("END"); } }
标签:面试题,abc,打印,private,ABC,线程,CountDownLatch,多线程,Condition From: https://www.cnblogs.com/jacksonshi/p/16795890.html