class Ticket implements Runnable
{
private int tick = 100;
boolean flag = true;
public void run()
{
if(flag)
{
while(true)
{
synchronized(this)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--code--:"+tick--);
}
}
}
}
else
while(true)
show();
}
public synchronized void show()
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"...sale........:"+tick--);
}
}
}
class BankDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{Thread.sleep(10);}catch(Exception e){}
t.flag=false;
t2.start();
}
}
为什么结果看起来一个线程在运行?
Thread-0--code--:100
Thread-0--code--:99
Thread-0--code--:98
Thread-0--code--:97
Thread-0--code--:96
Thread-0--code--:95
Thread-0--code--:94
……
Thread-0--code--:5
Thread-0--code--:4
Thread-0--code--:3
Thread-0--code--:2
Thread-0--code--:1
我执行了好几次,都是Thread-0在运行。 |
|