下列示例中,在主方法中将Ticket类中标记置为false后(t.setFlag();),运行结果为何t1线程还是在执行同步代码块中内容,既然为false,应该执行同步函数中内容才对呀,求大神解惑~~~~~~~~
class Ticket implements Runnable
{
private int num = 200;
private boolean flag = true;
public void run()
{
if(flag)//为true就执行同步代码块。
while(true)
{
synchronized(this)
{
if(num>0)
{
try{Thread.sleep(10);}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".....code.........."+num--);
}
}
}
else//为false就执行同步函数。
while(true)
{
show();
}
}
/*
将标记改为false。
*/
public void setFlag()
{
flag = false;
} public synchronized void show()//this
{
if(num>0)
{
try{Thread.sleep(10);}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"............func....."+num--);
}
}
}class ThisLockDemo
{
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(InterruptedException e){}
//在开启了t1后,将标记置为false。
t.setFlag(); t2.start();
}
}
class Ticket implements Runnable
{
private int num = 200;
private boolean flag = true;
public void run()
{
if(flag)//为true就执行同步代码块。
while(true)
{
synchronized(this)
{
if(num>0)
{
try{Thread.sleep(10);}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".....code.........."+num--);
}
}
}
else//为false就执行同步函数。
while(true)
{
show();
}
}
/*
将标记改为false。
*/
public void setFlag()
{
flag = false;
} public synchronized void show()//this
{
if(num>0)
{
try{Thread.sleep(10);}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"............func....."+num--);
}
}
}class ThisLockDemo
{
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(InterruptedException e){}
//在开启了t1后,将标记置为false。
t.setFlag(); t2.start();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货