/*
// 死锁
// 死锁,将两个或多个锁相互嵌套,就由死锁的现象。
// 单例设计模式:
// 饿汉式:
class Single
{
private static Single s=new Single();
public static Single getinstance()
{
return s;
}
}
//懒汉式:
// 存在安全隐患!
class Single
{
public static Single s=null;
public static Single getinstance()
{
if(s==null)
{
//线程在此处冻结Thread.sleep(time),则出现多次实例化!
return s=new Single();
}
}
}
*/
class Lock implements Runnable
{
private boolean flag;
Lock(boolean flag)
{
this.flag=flag;
}
public void run()
{
if(flag)
{
while(true)
{
synchronized(Mylock.mylocka)
{
System.out.println("this is mylocka from if");
synchronized(Mylock.mylockb)
{
System.out.println("this is mylockb from if");
}
}
}
}
else
{
while(true)
{
synchronized(Mylock.mylockb)
{
System.out.println("this is mylockb from else");
synchronized(Mylock.mylocka)
{
System.out.println("this is mylocka from else");
}
}
}
}
}
}
class Mylock
{
static Object mylocka=new Object();
static Object mylockb=new Object();
}
class 线程笔记_死锁
{
public static void main(String[] args)
{
Thread t1=new Thread(new Lock(true));
Thread t2=new Thread(new Lock(false));
t1.start();
t2.start();
}
}