本帖最后由 张号 于 2013-3-11 17:47 编辑
不知道为什么 总是只有一个线程运行- //售票窗口
- public class SealWindow
- {
- public static void main(String[] args)
- {
- new Thread(new TicketSealCenter(), "1号窗口").start();
- new Thread(new TicketSealCenter(), "2号窗口").start();
- new Thread(new TicketSealCenter(), "3号窗口").start();
- new Thread(new TicketSealCenter(), "4号窗口").start();
- new Thread(new TicketSealCenter(), "5号窗口").start();
- new Thread(new TicketSealCenter(), "6号窗口").start();
- }
- }
- // 售票中心
- class TicketSealCenter implements Runnable
- {
- private void sale() throws Exception
- {
- Ticket ticket = new Ticket();
- // 售票中心分配火车票
- ticket.setTicketNum(10);
- while (ticket.isEmple())
- {
- System.out.println(Thread.currentThread().getName() + "售出一张"
- + "还剩下" + ticket.getTicketNum() + "张票");
- if (ticket.getTicketNum() == 0)
- {
- System.out.println("票已经卖完了,明天再来吧!!!");
- }
- }
- }
- @Override
- public void run()
- {
- try
- {
- //同步代码块
- synchronized (TicketSealCenter.class)
- {
- sale();
-
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- // 火车票类
- class Ticket
- {
- private int ticketNum; // 火车票张数
- // 获得火车票的数量
- public int getTicketNum()
- {
- return ticketNum;
- }
- // 设置火车票数量
- public void setTicketNum(int ticketNum)
- {
- this.ticketNum = ticketNum;
- }
- // 判断是否有票
- public boolean isEmple() throws Exception
- {
- if (ticketNum > 0)
- {
- ticketNum--;
- Thread.sleep(1000);
- return true;
- }
- else
- {
- System.exit(0);
- return false;
- }
- }
- }
复制代码 |