Java實現賣票程序(兩種線程實現)


 1 /**
 2  * 2019年8月8日16:05:05
 3  * 目的:實現火車站賣票系統(第一種創建線程的方式)
 4  * @author 張濤
 5  *
 6  */
 7 
 8 //第一種方式直接繼承Thread來創建線程
 9 class T1 extends Thread
10 {
11     //加static的原因是:每次new一個對象出來,該對象就會有一個tickets屬性,這樣的話就相當於賣2倍票數,當然錯誤
12     private static int tickets = 1000;
13     //加static的原因是:確定同步的是同一個str,原理同上。
14     static String str = new String ("start");
15     //重寫run方法
16     public void run()
17     {
18         while(true)
19         {
20             synchronized(str)//同步代碼塊
21             {
22                 if(tickets > 0)
23                 {
24                     System.out.printf("%s線程正在運行,第%d張票正在出售\n",Thread.currentThread().getName(),tickets);
25                     tickets--;
26                 }
27             }
28             
29         }
30         
31     }
32 }
33 
34 public class Ticket_1 
35 {
36     public static void main(String[] args)
37     {
38         //兩個對象,兩個線程
39         T1 tic1 = new T1();
40         T1 tic2 = new T1();
41         
42         tic1.start();
43         tic2.start();
44     }
45 }
 1 /**
 2  * 2019年8月8日17:04:45
 3  * 目的:實現火車站的賣票系統(第二種創建線程的方式)
 4  * @author 張濤
 5  *
 6  */
 7 
 8 //創建線程的第二種方式
 9 class T2 implements Runnable
10 {
11     /*相較於第一種創建線程的方式,
12      * 這里不需要加static,
13      * 因為該創建方式是同一個對象里面的不同線程,
14      * 第一種創建方式是不同對象的不同線程,
15      */
16     private int tickets = 10000;
17     String str = new String ("start");
18     
19     //重寫run
20     public void run()
21     {
22         while(true)
23         {
24             //同步代碼塊
25             synchronized (str)
26             {
27                 if(tickets > 0)
28                 {
29                     System.out.printf("%s線程正在運行,正在賣出剩余的第%d張票\n",Thread.currentThread().getName(),tickets);
30                     /*
31                      *    調用Thread類中的currentThread()方法到達當前線程,再通過getName()方法獲取當前線程的名稱 
32                     */
33                     tickets--;
34                 }
35             }
36         }
37     }
38 }
39 
40 public class Ticket_2 
41 {
42     public static void main(String[] args)
43     {
44         //構建T2的對象
45         T2 tt = new T2();
46         //用同一個對象構造里面的兩個線程
47         Thread t1 = new Thread (tt);
48         Thread t2 = new Thread (tt);
49         t1.setName("南京站");
50         t2.setName("南京南站");
51         
52         //開啟線程
53         t1.start();
54         t2.start();
55     }
56 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM