一、如今有線程 T一、T2 和 T3。你如何確保 T2 線程在 T1 以後執行,而且 T3 線程在 T2 以後執行?面試
這個線程面試題一般在第一輪面試或電話面試時被問到,這道多線程問題爲了測試面試者是否熟悉join方法的概念。答案也很是簡單——能夠用 Thread 類的join方法實現這一效果。多線程


1 public class Test { 2 3 public static void main(String[] args) throws InterruptedException { 4 Thread t1 = new Thread() { 5 public void run() { 6 System.out.println("1"); 7 } 8 }; 9 Thread t2 = new Thread() { 10 public void run() { 11 System.out.println("2"); 12 } 13 }; 14 Thread t3 = new Thread() { 15 public void run() { 16 System.out.println("3"); 17 } 18 }; 19 20 t1.start(); 21 t1.join();//阻塞住直到t1完成 22 t2.start(); 23 t2.join(); 24 t3.start(); 25 System.out.println("end"); 26 } 27 }
二、兩線程奇偶數打印ide


1 public class Test { 2 static class SoulutionTask implements Runnable { 3 static int value = 0; 4 5 @Override 6 public void run() { 7 while (value <= 100) { 8 synchronized (SoulutionTask.class) { 9 System.out.println(Thread.currentThread().getName() + ":" + value++); 10 SoulutionTask.class.notify(); 11 try { 12 SoulutionTask.class.wait(); 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } 16 } 17 } 18 } 19 } 20 21 public static void main(String[] args) throws InterruptedException { 22 new Thread(new SoulutionTask(), "偶數").start(); 23 new Thread(new SoulutionTask(), "奇數").start(); 24 } 25 }
N個線程循環打印


1 public class Test implements Runnable { 2 private static final Object LOCK = new Object(); 3 /** 4 * 當前即將打印的數字 5 */ 6 private static int current = 0; 7 /** 8 * 當前線程編號,從0開始 9 */ 10 private int threadNo; 11 /** 12 * 線程數量 13 */ 14 private int threadCount; 15 /** 16 * 打印的最大數值 17 */ 18 private int maxInt; 19 20 public Test(int threadNo, int threadCount, int maxInt) { 21 this.threadNo = threadNo; 22 this.threadCount = threadCount; 23 this.maxInt = maxInt; 24 } 25 26 @Override 27 public void run() { 28 while (true) { 29 synchronized (LOCK) { 30 // 判斷是否輪到當前線程執行 31 while (current % threadCount != threadNo) { 32 if (current > maxInt) { 33 break; 34 } 35 try { 36 // 若是不是,則當前線程進入wait 37 LOCK.wait(); 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } 41 } 42 // 最大值跳出循環 43 if (current > maxInt) { 44 break; 45 } 46 System.out.println("thread" + threadNo + " : " + current); 47 current++; 48 // 喚醒其餘wait線程 49 LOCK.notifyAll(); 50 } 51 } 52 } 53 54 public static void main(String[] args) { 55 int threadCount = 3; 56 int max = 100; 57 for (int i = 0; i < threadCount; i++) { 58 new Thread(new Test(i, threadCount, max)).start(); 59 } 60 } 61 }