[ 本帖最后由 csatshell 于 2013-3-13 22:49 编辑 ]\n\n兄弟,你的程序运行后,只有1号窗口买票,原因是你的同步代码块的锁选择的问题 看如下代码(更改你的锁标志)
//售票窗口
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(100); while (ticket.isEmple())
{
System.out.println(Thread.currentThread().getName() + "售出一张"
+ "还剩下" + ticket.getTicketNum() + "张票");
if (ticket.getTicketNum() == 0)
{
System.out.println("票已经卖完了,明天再来吧!!!");
} }
} //@Override
Object obj=new Object();//添加的
public void run()
{
try
{
synchronized (obj)
{
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(1);
return true;
}
else
{
System.exit(0);
return false;
}
}}
|
-
d.jpg
(63.36 KB, 下载次数: 25)
|