class Ticket implements Runnable
{
private int tick=1000; --------------------------------(2).
Object obj=new Object();
boolean flag=true;
public void run()
{
if(flag)
{
while(true)
{
synchronized(obj) // -------------------(1)
{
if(tick>0)
{
try
{
Thread.sleep(10);
}
catch (Exception e)
{
System.out.println("执行");
}
System.out.println(Thread.currentThread().getName()+"....code...."tick--);
}
}
}
}
else
while(true)
show(); //2.那么这是静态方法怎样调用的呢?
}
public synchronized void show() -------------------------------------------(3)
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"....show...."+tick--);
}
}
}
class TicketDemo3
{
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;
t2.start();
}
}
为什么会打印0?
而如果在(1)处的括号里面改成this就行
而如果把(2)和(3)语句加上static则会出错,而把(1)处换成Ticket.class为什么可以?
详解
|