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;
}
}
本文介绍了Java中实现单例模式的两种方法——懒汉式和饿汉式,并探讨了同步代码块及同步方法在确保线程安全方面的作用。
716

被折叠的 条评论
为什么被折叠?



