Java|java 实现3个线程 依次打印ABC,并且循环10次

【Java|java 实现3个线程 依次打印ABC,并且循环10次】网上看到一个题目,要求3个线程依次打印ABC,并且循环10次,网上的版本比较多,这个是我实现的一个版本,共用一个Runnable对象,有点小缺陷,无法关联线程的名
字。

package com.mythread.test; import java.util.concurrent.atomic.AtomicInteger; public class TestAsynTreadXunlei { public static void main(String argv[]) {AtomicInteger synObj = new AtomicInteger(0); Runnable r = new PrintThread(synObj); try { Thread a = new Thread(r, "A"); Thread b = new Thread(r, "B"); Thread c = new Thread(r, "C"); a.start(); b.start(); c.start(); } catch (Exception e) { e.printStackTrace(); } } }class PrintThread implements Runnable { private AtomicInteger synObj; public PrintThread(AtomicInteger synObj) { this.synObj = synObj; } @Override public void run() { print(); } public void print() { for (int i = 0; i < 10; i++) { try {synchronized (synObj) { if (synObj.get() % 3 == 0) { System.out.println("A"); synObj.set(synObj.get() + 1); } else if (synObj.get() % 3 == 1 ) { System.out.println("B"); synObj.set(synObj.get() + 1); } else if (synObj.get() % 3 == 2 ) { System.out.println("C"); synObj.set(synObj.get() + 1); } }} catch (Exception e) { e.printStackTrace(); } } } }


网上比较经典的一个版本(基于thread)

package com.mythread.test; import java.util.concurrent.atomic.AtomicInteger; public class TestAsynTreadXunlei { public static void main(String argv[]) {AtomicInteger synObj = new AtomicInteger(0); TestPrint a = new TestPrint(synObj, "A", 0); TestPrint b = new TestPrint(synObj, "B", 1); TestPrint c = new TestPrint(synObj, "C", 2); a.start(); b.start(); c.start(); } }class TestPrint extends Thread { private AtomicInteger synObj; private String name; private int flag; private int count = 0; public TestPrint(AtomicInteger synObj, String name, int flag) { this.synObj = synObj; this.name = name; this.flag = flag; } @Override public void run() { while (true) { synchronized (synObj) { if (synObj.get() % 3 == flag) { synObj.set(synObj.get() + 1); System.out.println(name); count++; synObj.notifyAll(); if (count == 10) { break; } } else { try { synObj.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } }




    推荐阅读