老紫竹,为什么SellThread方法中if(b==false)和if(b=false)执行结果会不一样啊...class TicketsSystem
{
public static void main(String[] args)
{
SellThread st=new SellThread();
new Thread(st).start();
try
{
Thread.sleep(1);
}
catch(Exception e)
{
e.printStackTrace();
}
st.b=true;
new Thread(st).start();
//new Thread(st).start();
//new Thread(st).start();
}
}class SellThread implements Runnable
{
int tickets=100;
Object obj=new Object();
boolean b=false;
public void run()
{
if(b==false)
{
while(true)
sell();
}
else
{
while(true)
{
synchronized(obj)//同步块
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("obj:"+Thread.currentThread().getName()+" sell tickets:"+tickets);
tickets--;
}
}
}
}
}
public synchronized void sell()//同步方法
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("sell:"+Thread.currentThread().getName()+" sell tickets:"+tickets);
tickets--;
}
}
}
{
public static void main(String[] args)
{
SellThread st=new SellThread();
new Thread(st).start();
try
{
Thread.sleep(1);
}
catch(Exception e)
{
e.printStackTrace();
}
st.b=true;
new Thread(st).start();
//new Thread(st).start();
//new Thread(st).start();
}
}class SellThread implements Runnable
{
int tickets=100;
Object obj=new Object();
boolean b=false;
public void run()
{
if(b==false)
{
while(true)
sell();
}
else
{
while(true)
{
synchronized(obj)//同步块
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("obj:"+Thread.currentThread().getName()+" sell tickets:"+tickets);
tickets--;
}
}
}
}
}
public synchronized void sell()//同步方法
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("sell:"+Thread.currentThread().getName()+" sell tickets:"+tickets);
tickets--;
}
}
}
if(b==false) //这个是根据b的值来判断的,如果b是false那么整体就是true,如果b是true那么整体就是false.
{
······
public void run()
{
//假如1:是if(b=false),刚开始执行的时候把false赋给了b,if条件不成立,执行else;
//假如2:是if(b==false),刚开始条件成立,执行if里面的代码,再开启线程以后if条件不成立,执行else;
if(b==false)
{
while(true)
sell();
}
else
{
while(true)
{
//假如2(if(b==false)): 把obj改成this锁定的就是一个对象了啊!结果就会一样。
synchronized(obj)//锁定的是obj这个对象;。
{
······
}
}
}
/*
*锁定的是当前对象。 */
public synchronized void sell()//同步方法
{
······
}
就知道这么多了啊
呵呵.