本帖最后由 姿_`态 于 2014-6-26 10:12 编辑
/*
程序打印的是code和show交替。
有一点不明白,就是主方法中,t1线程开启之后,把flag改为false,接下来,每次打印不都应该是show?
*/
class TicketDemo4
{
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();
}
}
class Ticket implements Runnable
{
Object obj=new Object();
private int tick=100;
boolean flag=true;
public void run()
{
if(flag)
{
while (true)
{
synchronized(obj)
{
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()+"show...."+tick--);
}
}
}
|
|