synchronized (窗口卖票的线程解决方案)_单例模式

1 public class SellTicket implements Runnable {
 2   // 定义100张票
 3   private int tickets = 100;
 4   //创建锁对象
 5   private Object obj = new Object();
 6 
 7   @Override
 8   public void run() {
 9     while (true) {
10       synchronized (obj) {
11         if (tickets > 0) {
12           try {
13             Thread.sleep(100);
14           } catch (InterruptedException e) {
15             e.printStackTrace();
16           }
17           System.out.println(Thread.currentThread().getName()+ "正在出售第" + (tickets--) + "张票");
18         }
19       }
20     }
21   }
22 }
23 
24  
25 
26  
27 
28 public class SellTicketDemo {
29   public static void main(String[] args) {
30     // 创建资源对象
31     SellTicket st = new SellTicket();
32 
33     // 创建三个线程对象
34     Thread t1 = new Thread(st, "窗口1");
35     Thread t2 = new Thread(st, "窗口2");
36     Thread t3 = new Thread(st, "窗口3");
37 
38     // 启动线程
39     t1.start();
40     t2.start();
41     t3.start();
42   }
43 }

public class SellTicket implements Runnable {
  // 定义100张票
  private int tickets = 100;
  //创建锁对象
  private Object obj = new Object();


  @Override
  public void run() {
    while (true) {
      synchronized (obj) {
        if (tickets > 0) {
          try {
            Thread.sleep(100);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName()+ "正在出售第" + (tickets--) + "张票");
        }
      }
    }
  }
}


 


 


public class SellTicketDemo {
  public static void main(String[] args) {
    // 创建资源对象
    SellTicket st = new SellTicket();


    // 创建三个线程对象
    Thread t1 = new Thread(st, "窗口1");
    Thread t2 = new Thread(st, "窗口2");
    Thread t3 = new Thread(st, "窗口3");


    // 启动线程
    t1.start();
    t2.start();
    t3.start();
  }
}


44 
45  
posted @ 2017-08-13 19:45  纯洁的赤子之心  阅读(314)  评论(0)    收藏  举报