有关设计模式

一.单例设计模式

1.饱汉模式

public class Singleton {
	
	public static Singleton instance=null;
	private Singleton(){}; //构造函数私有化,为了阻止其他实例化对象
	public static  Singleton getInstance(){
		
		if(instance==null){
			instance = new Singleton();
		}
		return instance;
		
	}
}

饱汉模式不适用于多线程,例如当线程A想得到instance ,发现instance 为空,线程B也需要实例化instance,这时候就有两个instance对象。

 

2.饥饿模式

public class Singleton {
	
	public static Singleton instance=null;
	private Singleton(){}; 
	public static synchronized Singleton getInstance(){
		
		if(instance==null){
			instance = new Singleton();
		}
		return instance;
		
	}
}

 饥饿模式与饱汗模式唯一区别就是加个synchronized,加上synchronized后实现了线程的互斥访问getInstance()方法,从而保证了线程安全

synchronized指的是线程调用synchronized修饰的方法,synchronized会锁定当前对象,其他想访问这个对象会等着当前对象synchronized执行完修饰的代码。

 

 -------------------------

二.线程死锁问题

线程1 上两个AB 锁 ,先上锁A 后上锁B,线程2上,先上B锁后上A锁。

二.有关多线程 wait sleep区别

sleep  是Thread类的的静态方法,sleep(xxx)用于使线程休眠 xx millis 毫秒,但是对象锁仍然存在

wait    是object类的方法  ,wait调用后,一个已经上锁的线程暂时放弃锁,让其它线程执行。

wait自己调用时候必配一个notify/notifyall用于唤醒其他线程的。

所以同步实现 用synchronized  或者 wait 结合notify

 

posted on 2014-10-24 20:48  夜雨星辰-  阅读(96)  评论(0编辑  收藏  举报