class _dead implements Runnable //实现Runnable接口
{
boolean x = false;
public void run()
{
while (true)
{
if (x)
{
synchronized (_locka.a)
{
System.out.println("if>>>locka");
synchronized (_lockb.b)
{
System.out.println("if>>>lockb");
}
}
}
else
{
synchronized (_lockb.b)
{
System.out.println("else....lockb");
synchronized (_locka.a)
{
System.out.println("else ... locka");
}
}
}
}
}
}
class _locka
{
public static _locka a = new _locka();
}
class _lockb
{
public static _lockb b = new _lockb();
}
class Test2
{
public static void main(String[] args)
{
_dead d = new _dead();
Thread t = new Thread(d);
t.start();
_dead d1 = new _dead();
d1.x=true;
Thread t1 = new Thread(d1);
t1.start();
}
}
5.9 Thread方法常用参数介绍
run负责线程中运行的代码
Thread(String name),构造的时候,传递线程名
getName()获取线程名
setName()设置线程名
Thread.currentThread().getName()获取线程名,在非Thread子类中使用
start()开启线程,JVM调用线程的run方法
5.9.1 安全高效的懒汉式
/*
单例模式中,懒汉不安全
写一个,你认为安全的,效率较高的单例模式,要求懒汉
*/
class Single
{
private Single(){}
private static Single s = null; //先给s变量赋null值
public static Single show()
{ //通过双if判断是否为null
if (s== null)
{
if (s ==null)
{
synchronized (Single.class) //静态方法同步指向class文件
{
s = new Single();
}
}else
{
return s;
}
}
return s;
}
}
class Test implements Runnable
{
public void run()
{
while (true)
{
Single s = Single.show();
System.out.println(s);
}
}
}
class Test4
{
public static void main(String[] args)
{
Test t = new Test();
Thread t1 = new Thread(t);
t1.start();