class Ticket implements Runnable
{
private int num=100;
Object obj=new Object();
boolean flag=true;
public void run()
{
if (flag)
{
while (true)
{
synchronized(obj)
{
if (num>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
}
System.out.println(Thread.currentThread().getName()+".....obj......."+num--);
}
}
}
}
else
while (true)
{
show();
}
}
public synchronized void show()
{
if (num>0)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
}
System.out.println(Thread.currentThread().getName()+".....syn......."+num--);
}
}
}
class SynLockDemo
{
public static void main(String[] args)
{
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
t.flag=false;
t2.start();
}
}
为什么运行结果是(部分)
Thread-0.....syn.......14
Thread-0.....syn.......13
Thread-0.....syn.......12
Thread-0.....syn.......11
Thread-0.....syn.......10
Thread-0.....syn.......9
Thread-0.....syn.......8
Thread-0.....syn.......7
Thread-0.....syn.......6
Thread-0.....syn.......5
Thread-0.....syn.......4
Thread-0.....syn.......3
Thread-0.....syn.......2
Thread-0.....syn.......1
只有syn的没有obj的?
|
|