黑马程序员技术交流社区
标题:
多线程同步函数的锁问题
[打印本页]
作者:
ZHMing
时间:
2013-12-6 14:18
标题:
多线程同步函数的锁问题
public class TicketDemo {
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
{
boolean flag = true;
private int ticket =100;
//Object obj=new Object();
public void run()
{
if(flag)
{
while(true)
{
synchronized(this)
{
if(ticket>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"....code==="+ticket--);
}
}
}
}
else
while(true)
show();
}
public synchronized void show(){
if(ticket>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"....show="+ticket--);
}
}
}
复制代码
主方法t.flag已经赋值成false了。run方法里不就一直调用show了么。为什么还会执行if(flag)
作者:
王家胜
时间:
2013-12-6 15:59
public class TicketDemo
{
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
{
boolean flag = true;
private int ticket = 100;
// Object obj=new Object();
public void run()
{
while (true)
{
synchronized (this)
{
if (flag)
{
if (ticket > 0)
{
try
{
Thread.sleep(10);
} catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()
+ "....code===" + ticket--);
}
}
else
while (true)
show();
}
}
}
public synchronized void show()
{
if (ticket > 0)
{
try
{
Thread.sleep(10);
} catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName() + "....show="
+ ticket--);
}
}
}
复制代码
if写在循环外了,进入while(true)就出不来了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2