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