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();
}
}
}
}