有三個執行緒名字分別是A、B、C,每個執行緒只能列印自己的名字,在螢幕上順序列印 ABC,列印10次。
阿新 • • 發佈:2019-01-04
今天去面試的時候,遇到的筆試題,當時沒有想到,回來學習記錄下。今天去面試的時候,遇到的筆試題,當時沒有想到,回來學習記錄下。
public class TestPrintOrder { public static void main(String[] args) { AtomicInteger atomic = new AtomicInteger(); Print tPrint = new Print(); Thread threadA = new ThreadTest("A", 0, tPrint, 10, atomic); Thread threadB = new ThreadTest("B", 1, tPrint, 10, atomic); Thread threadC = new ThreadTest("C", 2, tPrint, 10, atomic); threadA.start(); threadB.start(); threadC.start(); } } class ThreadTest extends Thread{ private String name = ""; private Integer id = 0; private Print tPrint = null; private int count = 0; AtomicInteger atomic = null; public ThreadTest(String name, Integer id, Print tPrint, int count, AtomicInteger atomic) { super(); this.name = name; this.id = id; this.tPrint = tPrint; this.count = count; this.atomic = atomic; } public void run(){ while(count > 0){ if(atomic.get() % 3 == id){ tPrint.printName(name); count --; atomic.getAndIncrement(); } } } } /** * 列印 */ class Print{ void printName(String name){ System.out.print(name); } }
1.設計上注意,把列印這個物件獨立出來,以便控制資源的同步
2.使用atomic類原子性控制執行緒的執行,此處的取模,相當於一個變數標識
3.如果是列印一遍,使用執行緒的join(),比較便捷。
public class TestPrintOrder1 { public static void main(String[] args) throws InterruptedException { Thread testA = new TestThread("A"); Thread testB = new TestThread("B"); Thread testC = new TestThread("C"); testA.start(); testA.join(); testB.start(); testB.join(); testC.start(); } } class TestThread extends Thread{ String name = ""; public TestThread(String name){ this.name = name; } public void run(){ System.out.print(name); } }