一、多线程下的单例设计模式
利用双重判断的形式解决懒汉式的安全问题和效率问题
//饿汉式 /*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(); } }
if...alock
else...block
锁上了,Thread-0拿a锁,Thread-1拿b锁
时间: 2024-10-05 19:40:38