我在Java中学习多线程的概念,在那里我遇到了这种非常有趣的行为。我在尝试各种创建线程的方法。现在所讨论的问题是我们何时扩展Thread
,而不是实现Runnable
接口。
另外,我知道实现Runnable
接口而不是扩展Thread
类是非常有意义的,但是为了这个问题,假设我们扩展了Thread
类。
让t
作为我扩展的Thread
类的实例,我有一个代码块要在背景中执行,它是在我的Thread
类的run()
方法中编写的。
它完美地运行在t.start()
的后台,但我有点好奇,称之为t.run()
方法。在主线程中执行的代码段!
t.start()
做了t.run()
不做的事情吗?
发布于 2014-08-29 01:48:08
这是全班学生所做的。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();
}
这是故意的行为。
发布于 2014-08-29 01:50:35
t.start()
只需执行它所说的操作:启动一个新线程,该线程执行run()
的部分代码。t.run()
是从当前工作线程(在您的例子中是主线程)对对象的函数调用。
请记住:只有在调用线程的start()
函数时,才会启动一个新线程,否则,调用它的函数(start()
除外)就等于在任何其他不同对象上调用一个普通函数。
发布于 2014-08-29 01:52:47
t.start()
发出本机调用,以便在新线程中实际执行run()
方法。t.run()
只是在当前线程中执行run()
。
现在,
顺便提一句,我知道实现可运行接口比扩展线程类更有意义。
实际上,遵循这两种方法(实现可运行线程或扩展线程)都是非常有意义的。这并不是说一个人在客观的意义上是不好的。实现Runnable的优势在于,您可以让类扩展另一个类(这可能会破坏OO设计)。
https://stackoverflow.com/questions/25565707
复制