有关设计模式

一.单例设计模式

1.饱汉模式

public class Singleton {
	
	public static Singleton instance=new Singleton();
	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 ,线程2上都有两个AB 锁 。线程1线上A锁后上锁B ,线程2先上B锁后上A锁,同时进行。

wait 没对应notify也会造成死锁。

三.有关多线程 wait sleep区别

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

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

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

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

四.java 模拟栈的实现

public class ArrayStack {
    Object [] array;
    int top;
    int size;
    int count;
    public ArrayStack(int size){
        this.size = size;
        this.top=-1;  //入栈时候需要先++ 到0
        this.count=0;
        array = new Object[size];
    }
    /**
     * 入栈操作
     */
    public void push(Object obj){
        if(isFull()){ 
            System.out.println("栈满了,不能进栈");
            return ;
        }else{
            top++;
            count++;
            this.array[top]=obj;
        }
    }
    /**
     * 出栈操作 
     */
    public Object pop(){
        if(isEmpty()){
            System.out.println("栈为空,没有数据可以出栈");
        }
        
        count--;
        return this.array[--top];
    }
    
    /**
     * 判断栈是否为空
     */
    public boolean isEmpty(){
        return this.count==0;
    }
    
    
    /**
     * 判断栈是否满了
     */
    public boolean isFull(){
        return this.count==size;
    }
}

 

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