首页 > 代码库 > 售票任务(线程)

售票任务(线程)

售票的线程方式一(thread):

 1 class SaleTickets extends Thread {
 2     static int num = 50; // 总票数 共享的数据,三个窗口同时操作同一份数据
 3     //static Object o = new Object();
 4     public SaleTickets (String name) {
 5         super(name);
 6     }
 7    // 重写run方法:卖票的任务
 8     public void run() {
 9        
10         while (true) {
11             synchronized ("hh") { //任意类型的对象,锁对象应该是同一个对象
12                 try {
13                     Thread.sleep(500);
14                 } catch (InterruptedException e) {
15                     // TODO: handle exception
16                     e.printStackTrace();
17                 }
18                 if(num > 0) {
19                     System.out.println(this.getName() + "卖了第" + num + "票");
20                     num--;
21                 
22                 } else {
23                     System.out.println("票已售完");
24                     break;
25                 }
26             }
27         
28             
29         }
30     }
31     
32 }
33 public class Demo4 {
34 
35     /**
36      * @param args
37      */
38     public static void main(String[] args) {
39         // TODO Auto-generated method stub
40        SaleTickets t1 = new SaleTickets("窗口1");
41        SaleTickets t2 = new SaleTickets("窗口2");
42        SaleTickets t3 = new SaleTickets("窗口3");
43        t1.start();
44        t2.start();
45        t3.start();
46     }
47 
48 }

售票的线程方式二(Runnable):

 1 class SaleTickets1 implements Runnable {
 2     static int num = 50;
 3      public void run() {
 4          while (true) {
 5              synchronized ("djj") {
 6                  if (num > 0) {
 7                         System.out.println(Thread.currentThread().getName() + "卖出第" + num + "张票");
 8                         num--;
 9                     } else {
10                         System.out.println("票已售尽");
11                          break;
12                     }
13              }
14             
15         }
16         
17     }
18 }
19 public class Demo8 {
20 
21     /**
22      * @param args
23      */
24     public static void main(String[] args) {
25         // TODO Auto-generated method stub
26         //创建实现类对象
27        SaleTickets1 st = new SaleTickets1();
28        // 创建三个线程对象
29        Thread t = new Thread(st, "窗口1");
30        Thread t1 = new Thread(st, "窗口2");
31        Thread t2 = new Thread(st, "窗口3");
32        t.start();
33        t1.start();
34        t2.start();
35     }
36 
37 }

 

售票任务(线程)