标签:style color ar java strong sp art 问题 on
一、多线程下的单例设计模式
利用双重判断的形式解决懒汉式的安全问题和效率问题
//饿汉式 /*class Single { private static final Single t = new Single(); private Single(){} public static Single getInstance() { return t; } } */ //懒汉式 class Single { private static Single t = null; private Single(){} public static Single getInstance() { if(t==null)//解决效率问题 { synchronized(Single.class)//解决安全问题 { if(t==null) t = new Single(); } } return t; } }
二、死锁示例
死锁:常见就是,同步的嵌套
面试时,会让写死锁程序,只要写的出来,就说明死锁已经理解
class Deadlock implements Runnable { private boolean flag; public Deadlock(boolean flag) { // TODO Auto-generated constructor stub this.flag = flag; } public void run() { if(flag) { while(true) synchronized (lock.A_LOCK) { System.out.println("if...alock"); synchronized (lock.B_LOCK) { System.out.println("if...block"); } } } else { while(true) synchronized (lock.B_LOCK) { System.out.println("else...block"); synchronized (lock.A_LOCK) { System.out.println("else...alock"); } } } } } class lock { public static final Object A_LOCK = new Object(); public static final Object B_LOCK = new Object(); } class Main { public static void main(String[] args) { Deadlock t1 = new Deadlock(true); Deadlock t2 = new Deadlock(false); Thread j1 = new Thread(t1); Thread j2 = new Thread(t2); j1.start(); j2.start(); } }
锁上了,Thread-0拿a锁,Thread-1拿b锁
JAVA学习第二十五课(多线程(四))- 单例设计模式涉及的多线程问题
标签:style color ar java strong sp art 问题 on
原文地址:http://blog.csdn.net/wjw0130/article/details/39941593