标签:
1 package com.test; 2 3 public class SaleTickets implements Runnable 4 { 5 private int ticketCount = 10;// 总的票数 6 Object mutex = new Object();// 锁 7 8 /** 9 * 卖票 10 */ 11 public void sellTicket() 12 { 13 synchronized (mutex)// 当操作的是共享数据时, 14 // 用同步代码块进行包围起来,这样在执行时,只能有一个线程执行同步代码块里面的内容 15 { 16 if (ticketCount > 0) 17 { 18 ticketCount--; 19 System.out.println(Thread.currentThread().getName() 20 + "正在卖票,还剩" + ticketCount + "张票"); 21 } 22 else 23 { 24 System.out.println("票已经卖完!"); 25 return; 26 } 27 } 28 } 29 30 public void run() 31 { 32 while (ticketCount > 0)// 循环是指线程不停的去卖票 33 { 34 sellTicket(); 35 /** 36 * 在同步代码块里面睡觉,和不睡效果是一样 的,作用只是自已不执行,也不让线程执行 37 * 所以把睡觉放到同步代码块的外面,这样卖完一张票就睡一会,让其他线程再卖,这样所有的线程都可以卖票 38 */ 39 try 40 { 41 Thread.sleep(100); 42 } 43 catch (InterruptedException e) 44 { 45 e.printStackTrace(); 46 } 47 } 48 } 49 }
下面是调用
1 package com.test; 2 3 public class TicketMain 4 { 5 6 public static void main(String[] args) 7 { 8 SaleTickets runTicekt = new SaleTickets(); 9 Thread th1 = new Thread(runTicekt, "窗口1"); 10 Thread th2 = new Thread(runTicekt, "窗口2"); 11 Thread th3 = new Thread(runTicekt, "窗口3"); 12 Thread th4 = new Thread(runTicekt, "窗口4"); 13 th1.start(); 14 th2.start(); 15 th3.start(); 16 th4.start(); 17 } 18 19 }
执行效果:
标签:
原文地址:http://www.cnblogs.com/yangtze-yufei/p/5448384.html