1 /** 2 * 1、創建線程數量為5的線程池 3 * 2、同時運行5個買票窗口 4 * 3、總票數為100,每隔一秒鍾賣一張票 5 * @author Administrator 6 * 7 */ 8 public class Window { 9 10 static int tickets = 100; 11 static String string = ""; 12 13 public static void main(String[] args) { 14 ExecutorService service = Executors.newFixedThreadPool(5); 15 service.execute(new Runnable() { 16 @Override 17 public void run() { 18 while (tickets > 0) { 19 synchronized (string) { 20 try { 21 if (tickets > 0) { 22 System.out.println(Thread.currentThread().getName() 23 + "賣出了第" + (tickets--) + "張票"); 24 Thread.sleep(1000); 25 } 26 27 } catch (Exception e) { 28 e.printStackTrace(); 29 } 30 } 31 } 32 33 } 34 }); 35 //關閉線程池 36 service.shutdown(); 37 } 38 39 }