2014-08-29 44 views
5

我正在学习Java中的多线程概念,在这里我遇到了这个非常有趣的行为。我正在尝试各种创建线程的方式。现在的问题是我们延长Thread,而不是实现Runnable接口。Java中有趣的线程行为

在附注中,我知道它实现了Runnable接口的完美OO感,而不是扩展Thread类,但对于此问题的目的,假设我们扩展了Thread类。

t是我的我的扩展Thread类的实例,我有一个代码块中是我的我的Thread类的run()方法中写后台执行。

它与t.start()在后台完美运行,但我有点好奇,并调用t.run()方法。这段代码在主线程中执行!

t.start()这样做t.run()不是吗?

+4

我相信你可以在这里找到答案(这威力实际上打破你的面向对象的设计。): HTTP: //stackoverflow.com/questions/8579657/java-whats-the-difference-between-thread-start-and-runnable-run http://stackoverflow.com/questions/15841301/difference-between-running-and -starting-a-thread – 2014-08-29 09:49:37

+0

http:// stackoverflow。com/a/13134221/3436942告诉你简单易懂的语言的区别。很多** t.start(); **正在创建/创建一个新线程,而** t.run(); **只是在主线程上调用它 – jbutler483 2014-08-29 09:51:02

回答

8

这就是班级所要做的。 t.start()实际上会启动一个新线程,然后在该线程中调用run()。如果直接调用run(),则在当前线程中运行它。

public class Test implements Runnable() { 
    public void run() { System.out.println("test"); } 
} 

... 

public static void main(String...args) { 
    // this runs in the current thread 
    new Test().run(); 
    // this also runs in the current thread and is functionally the same as the above 
    new Thread(new Test()).run(); 
    // this starts a new thread, then calls run() on your Test instance in that new thread 
    new Thread(new Test()).start(); 
} 

这是打算的行为。

+0

哇,真棒解释!谢谢您的回答。 :) – avismara 2014-08-29 09:56:23

1

t.start()只是做它说的:启动一个新的线程,执行run()的代码部分。 t.run()是一个对象的函数调用,从当前工作线程(在你的情况下,主线程)。请注意:只有在调用线程函数start()时,才会启动一个新线程,否则,调用它的函数(start()除外)与在任何其他不同对象上调用普通函数相同。

+0

谢谢你的回答。 :) – avismara 2014-08-29 10:02:55

0

t.start()进行本地调用,以在新线程中实际执行run()方法。 t.run()仅在当前线程中执行run()

现在,

在一个侧面说明,我知道,这是绝对OO意义上实现Runnable接口,而不是扩展Thread类

事实上,它使完美 OO感遵循这两种方法(实现Runnable或扩展Thread)。从OO的角度来看,这并不是一件坏事。您通过实施获得优势的Runnable是,你可以让你的类扩展另一个类

+0

s /主线程/当前线程/,AFAIK。 – DarkDust 2014-08-29 09:57:16

+0

我当时正在谈论当前的情况。如果您打算将特性和功能添加到“线程”,那么扩展“线程”类是有意义的。如果你只是想创建一个新的线程,实现'Runnable'类。 :) – avismara 2014-08-29 09:58:04

+0

@DarkDust - 我没有得到你。 – TheLostMind 2014-08-29 09:58:37