Java 数量为5的线程池同时运行5个窗口买票,每隔一秒钟卖一张票


 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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM