開啟3個線程,這3個線程的ID分别為A、B、C,
* 每個線程将自己的ID在螢幕上列印10遍,要求輸出結果必須按ABC的順序顯示;
* 如:ABCABC….依次遞推。
序輸出ABC用synchronized的代碼實作
/**
* 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();
}
}
}
}
}
}
}