多线程之——实现循环打印"abc"

问题:有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC…
思路:可以使用同步多线程对打印字符的控制
【多线程之——实现循环打印"abc"】

public class CirclePrintABC { public static void main(String args[]) { SingleInstance si = SingleInstance.newInstance(); Thread a = new Thread(new PrintThread(si, 'a')); Thread b = new Thread(new PrintThread(si, 'b')); Thread c = new Thread(new PrintThread(si, 'c')); a.start(); b.start(); c.start(); } }class PrintThread implements Runnable { SingleInstance si; char str; public PrintThread(SingleInstance si, char str) { this.si = si; this.str = str; } public void run() { for (int i = 0; i < 10; i++) { synchronized (si) { while (str != si.getPrintStr()) { try { si.wait(); //这里是si的wait方法,wait方法不是Thread的 } catch (Exception e) {} } System.out.println(str); si.setPrintStr(); si.notifyAll(); } } } } class SingleInstance { static SingleInstance singleInstance = null; private char printStr = 'a'; public static SingleInstance newInstance() {//单例模式 if (singleInstance == null) { singleInstance = new SingleInstance(); } return singleInstance; } public char getPrintStr() { return this.printStr; } public char setPrintStr() { printStr = (char) (printStr + 1); if (printStr == 'd') { printStr = 'a'; } return printStr; }}



    推荐阅读