多線程-有序輸出

/**
 * 讓四個線程順序輸出1-12:
 *  Thread-0 : 1
    Thread-1 : 2
    Thread-2 : 3
    Thread-3 : 4
    Thread-0 : 5
    Thread-1 : 6
    Thread-2 : 7
    Thread-3 : 8
    Thread-0 : 9
    Thread-1 : 10
    Thread-2 : 11
    Thread-3 : 12
 * @author peiwenc
 */
public class ThreadTestByPeiwenc {
 public static void main(String[] args) {
  PrintNum2 printNum = new PrintNum2();
  for (int i = 0; i < 4; i++) {
   new Thread(printNum).start();
  }
 }
}
class PrintNum2 implements Runnable {
 private int num = 1; // 線程間共享數據
 private boolean isAlive = true; // 線程存活標誌
 private int sequence = 0; // 控制線程順序執行的標示
 private synchronized void add(int threadNum) {
  while (sequence % 4 != threadNum) { 
  try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  if (num < 13) {
   System.out.println(Thread.currentThread().getName() + " : " + num);
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  } else {
   isAlive = false;
  }
  num++;
  sequence++;
  this.notifyAll();
 }
 public void run() {
  while (isAlive) {
   add(Integer.parseInt(Thread.currentThread().getName()
     .replace("Thread-", "")));
  }
 }
}
相關文章
相關標籤/搜索