class TicketRunnable implements Runnable
{
private int tick = 1000;
boolean flag = true;
public void setFlag(boolean flag)
{
this.flag = flag;
}
public void run()
{
show();
}
private void show()
{
if(flag)
{
while(true)
{
synchronized(TicketRunnable.class)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println("线程一:"+"..."+tick--);
}
}
}
}
else
{
while(true)
{
synchronized(TicketRunnable.class)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(InterruptedException e){}
System.out.println("线程2:"+"..."+tick--);
}
}
}
}
}
}
public class TicketExe {
public static void main(String[] args)
{
/*
TicketDemo t1 = TicketDemo.getTicketDemo();
TicketDemo t2 = TicketDemo.getTicketDemo();
t1.start();
t2.start();*/
TicketRunnable t = new TicketRunnable();//如何区分这两个同步线程
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{Thread.sleep(15);}catch(Exception e){}
t.setFlag(false);
t2.start();
}
}
上面的程序多线程可以跑,运行正常,但是我把TicketRunnable类的锁位置稍微变一下,放在while循环的外面,多线程就跑不起来了,怎么回事?
大神求解!
锁放在while循环 的外面代码如下:
public class TicketRunnable implements Runnable
{
private int tick = 1000;
boolean flag = true;
public void setFlag(boolean flag)
{
this.flag = flag;
}
public void run()
{
show();
}
private void show()
{
if(flag)
{
synchronized(TicketRunnable.class)
{
while(true)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println("线程一:"+"..."+tick--);
}
}
}
}
else
{
synchronized(TicketRunnable.class)
{
while(true)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(InterruptedException e){}
System.out.println("线程2:"+"..."+tick--);
}
}
}
}
}
}
|
|