51,408
社区成员
发帖
与我相关
我的任务
分享package tv.lufei.one;
//第二种
public class Test6 implements Runnable{
private A a = new A();
private B b = new B();
public static void main(String[] args) {
new Test6();
}
public Test6() {
// System.out.println();为什么加了这个注释,就不是死锁了呀?
new Thread(this).start();
b.say(a);
}
@Override
public void run() {
// System.out.println("执行了run");
a.say(b);
}
}
class A{
public synchronized void say(B b){
System.out.println("A说:你先放人,我就给钱!");
b.get();
}
public synchronized void get(){
System.out.println("A:救了人,付出了钱!");
}
}
class B{
public synchronized void say(A a){
System.out.println("B说:你先给钱,我就放人!");
a.get();
}
public synchronized void get(){
System.out.println("B:放了人,拿到了钱!");
}
}class A{
public synchronized void say(B b){
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("A说:你先放人,我就给钱!");
b.get();
}
public synchronized void get(){
System.out.println("A:救了人,付出了钱!");
}
}
class B{
public synchronized void say(A a){
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("B说:你先给钱,我就放人!");
a.get();
}
public synchronized void get(){
System.out.println("B:放了人,拿到了钱!");
}
}