线程同步2

来源:互联网 发布:应采儿长相知乎 编辑:程序博客网 时间:2024/06/05 14:58

public class Test1{
public static void main(String []args){
ThreadSychonized tt=new ThreadSychonized();
new Thread(tt).start();
try{
 Thread.sleep(10);
 }catch(InterruptedException se){}
 tt.flag=true;
new Thread(tt).start();


}


}

 

class ThreadSychonized implements Runnable{
int ticket=100;
boolean flag=false;
public void run(){
if(flag){//执行sail方法
while(true)
  sail();
  }else{
  synchronized(this){
  if(ticket>0){
  try{
   Thread.sleep(10);
  }catch(InterruptedException se){}
 System.out.println(Thread.currentThread().getName() +":" +ticket--);
  }
  }

}
}

public synchronized void sail(){
 if(ticket>0){
  try{
   Thread.sleep(10);
  }catch(InterruptedException se){}
 System.out.println(Thread.currentThread().getName() +":" +ticket--);
}

}

}