码迷,mamicode.com
首页 > 编程语言 > 详细

售票任务(线程)

时间:2016-12-02 21:19:07      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:操作   tar   out   err   and   pre   bre   hand   main   

售票的线程方式一(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 }

 

售票任务(线程)

标签:操作   tar   out   err   and   pre   bre   hand   main   

原文地址:http://www.cnblogs.com/binzhihua-666/p/6126960.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!