開啓3個線程,這3個線程的ID分別爲A、B、C,
* 每一個線程將本身的ID在屏幕上打印10遍,要求輸出結果必須按ABC的順序顯示;
* 如:ABCABC….依次遞推。ide
序輸出ABC用synchronized的代碼實現this
/** * create by spy on 2018/5/31 */ public class ThreadShunXuPrint { public static void main(String[] args) { Object obj = new Object(); for (int i = 0; i < 3; i++) { new Thread(new printThread(obj, "" + (char) (i + 65), i, 121)).start(); } } static class printThread implements Runnable { private static Object object;//線程加鎖對象 private String threadName;//線程名稱要打印的字母 private int threadId;//線程指定的下標ID private static int count = 0;//已打印次數 private Integer totalCount = 0;//總打印次數 public printThread(Object object, String threadName, int threadId, Integer totalCount) { this.object = object; this.threadName = threadName; this.threadId = threadId; this.totalCount = totalCount; } @Override public void run() { synchronized (object) {//判斷該資源是否正在被使用 while (count < totalCount) { if (count % 3 == threadId) { //判斷當前已打印次取餘線程數相等打印不然等待 System.out.println(threadName); count++; object.notifyAll(); } else { try { object.wait(); } catch (Exception e) { System.out.println("線程" + threadName + "打斷了!"); e.printStackTrace(); } } } } } } }