本帖最后由 廖志强 于 2013-5-31 23:55 编辑
public class Ticket implements Runnable
{
//定义100张票
private int tickets = 100;
@Override
public void run()
{
while(true)
{
synchronized(this){
if(tickets>0)
{
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在卖出第"+(tickets--)+"张票");
}
}
}
}
}
public class Test
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t,"窗口1"); //对象1
Thread t2 = new Thread(t,"窗口2");//对象2
Thread t3 = new Thread(t,"窗口3");//对象3
Thread t4 = new Thread(t,"窗口4");//对象4
t1.start();
t2.start();
t3.start();
t4.start();
}
}
其实就是对象1,对象2,对象3,对象4,同时在强一张票,就会出问题,这时候我们就加了同步,这一百张四个对象多有机会买,就看是谁抢到了虚拟机
|