java|java 多线程打印ABC

方法千千中,开始看到这个,我立马想到了cyclicBarrier,能让ABC在打印在一组,可是控制不了ABC打印的顺序
【java|java 多线程打印ABC】
后来自己用了一个最简单的synchronize的循环实现了,可以感觉没什么成就感

最后看了网上一个例子,思路很有意思,但是也不是我想要的,代码还是分享一下,请高手一眼扫过:


package dirk.zhang; public class PrintABC { public static void main(String[] arg) { Data d = new Data(); Threadp p1 = new Threadp("a","b",d); Threadp p2 = new Threadp("b","c",d); Threadp p3 = new Threadp("c","a",d); p1.start(); p2.start(); p3.start(); } }class Threadp extends Thread { private finalString name; private finalString next; private finalData d; private int count = 10; Threadp(String name,String next,Data d) { this.name = name; this.next = next; this.d = d; } @Override public void run() { while(count>0) { if(d.flagName.equals(name)) synchronized (d) { System.out.print(name); d.flagName = next; count--; } } } private void printname() { System.out.println(name); } }class Data { public String flagName; public Data() { flagName = "a"; } }


怎么样,看完之后感觉也很平平淡淡,谁有什么更好的方法来showshow

    推荐阅读