技术交流群:233513714
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 }
44
45