/*
* 需求:现场写出一个线程死锁的例子
* 思想:使用同步代码块嵌套的形式实现线程死锁
* 步骤:1.创建两把锁,locka,lockb
2.创建两个线程,两把锁嵌套
*/
class Lock
{
public static final Object locka = new Object();
public static final Object lockb = new Object();
}
class DeadLock implements Runnable
{
boolean flag = true;
DeadLock(boolean flag){
this.flag = flag;
}
public void run(){
if(flag){
while(true)
synchronized(Lock.locka){
System.out.println(flag + ".... locka");
synchronized(Lock.lockb){
System.out.println(flag + ".....lockb");
}
}
}else{
while(true)
synchronized(Lock.lockb){
System.out.println(flag + ".... lockb");
synchronized(Lock.locka){
System.out.println(flag + ".....locka");
}
}
}
}
}
class LockDemo
{
public static void main(String[] args)
{
DeadLock d1 = new DeadLock(true);
DeadLock d2 = new DeadLock(false);
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
t1.start();
t2.start();
}
}
Java-线程$死锁
最新推荐文章于 2024-11-15 18:38:47 发布