代码如下:
class Ticket implements Runnable
{
private static int tick = 40;
public void run()
{
while(tick>0)//此处存在安全隐患
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--sale: "+tick--);
}
}
}
class TicketDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.start();
t2.start();
t3.start();
}
}
这个代码能加锁吗?
毕老师中的视频中,while(true),下面再用 if 判断,加锁问题可以解决。但是,却是一个无限循环。。 |
|