{
while(true)
{
sale();
}
}
else
{
while(true)
{
synchronized(str) //synchronized(this) ,监视当前对象
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+
" is saling ticket " + tickets--);
}
}
}
}
}
public synchronized void sale()
{
if(tickets>0)
{
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName()+" is saling ticket " + tickets--);
}
}
}
产生并启动第一个线程,这个线程不见得马上就开始运行,CPU可能还在原来的main线程上运行,并将str变量设置成了”method”。
银行问题的同步:
class CAdd
{
private static int sum = 0 ;
public synchronized static void add(int a)
{
int temp = sum ;
try
{
Thread.sleep(100) ;
}
catch(Exception e)
{}
temp = temp+a ;
sum = temp ;
System.out.println(sum);
共21页 第1页 第2页 第3页 第4页 第5页 第6页 第7页 第8页 第9页 第10页 第11页 第12页 第13页 第14页 第15页 第16页 第17页 第18页 第19页 第20页 第21页






