线程之同步的两种条件总结

来源:互联网 发布:男人知天命之年说说 编辑:程序博客网 时间:2024/04/25 01:29

同步的两种表现形式:
1.同步代码块
   synchronized(对象){

       需要同步的代码
}


2.同步函数: 使用的锁是this

  public synchronized void show(){

}


同步的作用:避免线程的安全隐患

 

单例


懒汉式

class Single{
   private static Single s=null;
   private Single(){}
   public static Single getInstance(){
       if(s==null)
          synchronized(Singel。class){
             if(s==null)
               s=new Single();
         }

         return s;

 

}


class Single{
   private static Single s=null;
   private Single(){}
   public static synchronized Single getInstance(){
      
      
          if(s==null)
              s=new Single();
       

         return s;

 

}


Single。getInstance();


饿汉式


class Single{
   private static Single s=new Single();
   private Single(){}
   public static Single getInstance(){
         return s;


}

 

 

}

原创粉丝点击