这道多线程的练习题,我明明加了同步锁,可还是出现负数的结果,实在想不通.求指教
package com.itheima5;
/*
* .定义一个类实现Runnable接口,卖票100张,四个线程,输出格式为“窗口1,还剩10张票”,指定窗口3卖第10张票
* */
public class SellTicket implements Runnable
{
int ticket=100;
@Override
public void run()
{
while(ticket>0)
{
synchronized(this)
{
try
{
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+
",还剩"+(--ticket)+"张票");
}
}
}
}
package com.itheima5;
public class SellTicketDemo
{
public static void main(String[] args)
{
SellTicket st=new SellTicket();
Thread t1=new Thread(st,"窗口1");
Thread t2=new Thread(st,"窗口2");
Thread t3=new Thread(st,"窗口3");
Thread t4=new Thread(st,"窗口4");
t1.start();
t2.start();
t3.start();
t4.start();
}
} |
|