單線程化的線程池

在這裏插入圖片描述
在這裏插入圖片描述

package com.youkeda.test.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Station2 {
   private static final ExecutorService threadpool = Executors.newSingleThreadExecutor();
   public static int tickCount= 20;
   
    public static void main(String[] args) {
      
        Window Station2 = new Window("Window-1");
        threadpool.execute(Station2);
        
    }
}
package com.youkeda.test.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Window implements Runnable {

    private String name;
  
    private static Object ob = new Object();
  
    public Window(String name) {
      this.name = name;
    }
  
    @Override
    public void run() {
      while (Station2.tickCount > 0) {
        synchronized (ob) {// 這個很重要,必須使用一個鎖,
          // 進去的人會把鑰匙拿在手上,出來後才把鑰匙拿讓出來
          if (Station2.tickCount > 0) {
            System.out.println(name + " 賣出了第 " + Station2.tickCount + " 張票");
            Station2.tickCount--;
          } else {
            System.out.println("票賣完了");
          }
        }
  
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章