同步代码块与同步方法

class   ThreadDemo1
{
public  static   void  main(String[] args)
{
TestThread tt  =new  TestThread();
new Thread(tt).start();
try{Thread.sleep(1);}catch(Exception e){}
tt.str=new  String("method");
new Thread(tt).start();
}
}
class  TestThread implements  Runnable
{
String str=new  String("");
int  tickets=100;
public  void   run()
{
if(str.equals("method"))
{
while(true)
{
sale();
}
}

else
{
while(true)
{
synchronized(this)
{
if(tickets>0)
{
try{
Thread.sleep(10);
}
catch(Exception e){}
System.out.println(Thread.currentThread().getName()+":is  ticket-"+tickets--);
}
}
}
}
}
public  synchronized  void  sale()
{
if(tickets>0)
{
try{
Thread.sleep(10);
}catch(Exception  e)
{}
System.out.println(Thread.currentThread().getName()+":ticket is:"+tickets--);
}
}
}

posted on 2012-03-09 08:38  平安夜  阅读(207)  评论(0编辑  收藏  举报