3個執行緒每個執行緒只能列印自己的名字,在螢幕上順序列印 ABC,列印10次
阿新 • • 發佈:2018-12-29
public class TeatPrintOrder { public static void main(String args[]){ AtomicInteger atomic = new AtomicInteger(); Print p = new Print(); ThreadTest a = new ThreadTest(p,"A",0,10,atomic); ThreadTest b = new ThreadTest(p,"B",1,10,atomic); ThreadTest c = new ThreadTest(p,"C",2,10,atomic); a.start();b.start();c.start(); } } class ThreadTest extends Thread{ String name=""; Integer id ; Print tPrint = null; int count; AtomicInteger atomic ; ThreadTest(Print p,String name,Integer id,int count,AtomicInteger atomic){ this.name = name ; this.id= id ; this.tPrint = p ; this.count = count ; this.atomic= atomic ; } public void run(){ while(count>0){ if((atomic.get() % 3) ==id){ tPrint.PrintName(name); atomic.getAndAdd(1); count--; } } } } class Print{ void PrintName(String name){ System.out.print(name); } }
1.設計上注意,把列印這個物件獨立出來,以便控制資源的同步
2.使用atomic類原子性控制執行緒的執行,此處的取模,相當於一個變數標識
3.如果是列印一遍,使用執行緒的join(),比較便捷。
更多的實現方法參考:http://blog.csdn.net/zheng0518/article/details/21728355static class MyThread extends Thread { public MyThread (final String name) { super (name); } @Override public void run () { System.out.print (currentThread ().getName ()); } } private static void printOnceV2 () throws InterruptedException { final MyThread threadA = new MyThread ("A"); final MyThread threadB = new MyThread ("B"); final MyThread threadC = new MyThread ("C"); threadA.start (); threadA.join (); // 等待 A 執行完,再開始 B threadB.start (); threadB.join (); // 等待 B 執行完,再開始 C threadC.start (); }