2013-10-02 29 views
0
public class Deadlock { 
    static class Friend { 
     private final String name; 
     public Friend(String name) { 
      this.name = name; 
     } 
     public String getName() { 
      return this.name; 
     } 
     public synchronized void bow(Friend bower) { 
      System.out.format("%s: %s" 
       + " has bowed to me!%n", 
       this.name, bower.getName()); 
      bower.bowBack(this); 
     } 
     public synchronized void bowBack(Friend bower) { 
      System.out.format("%s: %s" 
       + " has bowed back to me!%n", 
       this.name, bower.getName()); 
     } 
    } 

    public static void main(String[] args) { 
     final Friend alphonse = 
      new Friend("Alphonse"); 
     final Friend gaston = 
      new Friend("Gaston"); 
     new Thread(new Runnable() { 
      public void run() { alphonse.bow(gaston); } 
     }).start(); 
     new Thread(new Runnable() { 
      public void run() { gaston.bow(alphonse); } 
     }).start(); 
    } 
} 




/* 

new Thread(new Runnable() { 
       public void run() { gaston.bow(alphonse); } 
      }).start(); 

*/ 
在上面的代码

,我们通过创建一个匿名类的匿名对象创建new Thread(Runnable接口的子类?)Mutithreading和匿名类和对象

但是当我们通过这新的Runnable对象,它有它自己运行()方法重载。所以*新的线程对象仍然没有它的run()方法重载。*由调用新线程(....)。start是到仍然没有被覆盖的线程的run()! 我错了,导致此代码工作

+0

可能是一个计时问题。你的线程太快而死锁。对同步方法进行长时间的睡眠以强制死锁。 – Thilo

+0

我坚信你让我mate.this代码工作,,我想问的是它是如何工作的! – user2837260

+0

我们从来没有定义Thread对象的run()方法,但它的工作原理。 – user2837260

回答

0

从调用的Thread对象的start()documentation

public Thread(Runnable target) 

Parameters: 
target - the object whose run method is invoked when this thread is started. If null, this classes run method does nothing. 

run()方法的Runnable

2

是的,你错了。首先,你很困惑overloadingoverriding

第二,the javadoc of Thread说明如何创建线程:

有创建一个新的执行线程两种方式。一种是将一个类声明为Thread的子类。此子类应覆盖Thread类的运行方法。[...]

另一种创建线程的方法是声明一个实现Runnable接口的类。那个类然后实现了run方法。然后可以分配一个类的实例,在创建线程时作为参数传递并启动。

+0

我没有混淆过载或覆盖或甚至是这个问题的僵局。但无论如何,感谢您的帮助 – user2837260

+1

@ user2837260您使用了“oveloaded”,意思是“重写”(两次)。这就是JB所指的。 –

+0

噢..只是注意到..我的不好 – user2837260

1

每当你想知道的东西在JDK,just have a look如何工作的run()。在这种特殊情况下,这将是你会在Thread类发现:

public void run() { 
    if (target != null) { 
     target.run(); 
    } 
} 

显然,该方法定义和实现,以及实现说“叫传入的Runnable接口的run方法”。

+0

是的,谢谢...和书签:D – user2837260