多
线程编写避免死锁
死锁代码:
代码1:
class="java">
/**
* 线程同步死锁问题
*
* 造成原因:线程持a持有一个锁,线程b也持有一个锁,a线程想进入b线程中运行,b线程想
* 进入a线程中运行,a线程不释放锁,b线程也不释放锁。就这样就成为死锁,程序没有了反应。
* */
class Test implements Runnable
{
private boolean flag;
public Test(boolean flag) {
this.flag=flag;
}
@Override
public void run()
{
if(flag)
{
synchronized (Mylock.locka) {
System.out.println("if locka");
synchronized (Mylock.lockb) {
System.out.println("if lockb");
}
}
}
else
{
synchronized (Mylock.lockb) {
System.out.println("else lockb");
synchronized (Mylock.locka) {
System.out.println("else locka");
}
}
}
}
}
//锁类
class Mylock
{
static Object locka = new Object();
static Object lockb = new Object();
}
//测试
class DeathLockDemo{
public static void main(String[] args) {
Thread t1 = new Thread(new Test(true));
Thread t2 = new Thread(new Test(false));
t1.start();
t2.start();
}
}
运行结果: