java线程输出ABCD

package xufeng.java; public class Printer implements Runnable{ // 输出字符 String printStr = null; // 下一个输出对象 Printer nextPrinter = null; public Printer(String str) { printStr = str; }public void setNextPrinter(Printer nextPr) { nextPrinter = nextPr; }@Override public void run() { for (int i = 0; i < 10; i++) { synchronized (nextPrinter) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.print(printStr); nextPrinter.notifyAll(); }synchronized (this) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }} }

package xufeng.java; public class MainTest { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { Printer a = new Printer("A"); Printer b = new Printer("B"); Printer c = new Printer("C"); Printer d = new Printer("D"); // 设置前后关系 a.setNextPrinter(b); b.setNextPrinter(c); c.setNextPrinter(d); d.setNextPrinter(a); // 启动线程。相隔一秒以免初始输出顺序混乱 new Thread(a).start(); Thread.sleep(1000); new Thread(b).start(); Thread.sleep(1000); new Thread(c).start(); Thread.sleep(1000); new Thread(d).start(); } }



【java线程输出ABCD】转载于:https://blog.51cto.com/mk78x/1243447

    推荐阅读