求java大神解答!!!急急急!!!
编程实现JAVA中的死锁,要求建立两个线程,共享使用互斥资源,启动线程并休眠0.5秒后进入死锁状态...
编程实现JAVA中的死锁,要求建立两个线程,共享使用互斥资源,启动线程并休眠0.5秒后进入死锁状态
展开
1个回答
展开全部
//会给多少财富啊?
public class P
{
public static void main(String[] args)
{
final A a=new A();
final B b=new B();
Thread t1=new Thread()
{
public void run()
{
a.f1(b);
P.run();
}
};
Thread t2=new Thread()
{
public void run()
{
b.f1(a);
P.run();
}
};
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
static void run()
{
while(!Exit)
{
try
{
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
static boolean Exit=false;
}
class A
{
synchronized void f1(B b)
{
System.out.println("A.f1");
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
b.f1(this);
}
}
class B
{
synchronized void f1(A a)
{
System.out.println("B.f1");
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
a.f1(this);
}
}
public class P
{
public static void main(String[] args)
{
final A a=new A();
final B b=new B();
Thread t1=new Thread()
{
public void run()
{
a.f1(b);
P.run();
}
};
Thread t2=new Thread()
{
public void run()
{
b.f1(a);
P.run();
}
};
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
static void run()
{
while(!Exit)
{
try
{
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
static boolean Exit=false;
}
class A
{
synchronized void f1(B b)
{
System.out.println("A.f1");
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
b.f1(this);
}
}
class B
{
synchronized void f1(A a)
{
System.out.println("B.f1");
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
a.f1(this);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询