Java中有趣的线程行为
我在学习Java中多线程的概念时,遇到了这个非常有趣的行为。我正在试验各种创建线程的方法。现在的问题是当我们扩展Java中有趣的线程行为,java,multithreading,Java,Multithreading,我在学习Java中多线程的概念时,遇到了这个非常有趣的行为。我正在试验各种创建线程的方法。现在的问题是当我们扩展线程时,没有实现可运行接口 另一方面,我知道实现Runnable接口而不是扩展Thread类是非常有意义的,但是就这个问题而言,假设我们扩展了Thread类 让t作为扩展Thread类的实例,我有一个要在后台执行的代码块,它是在Thread类的run()方法中编写的 它使用t.start()在后台完美运行,但我有点好奇,于是调用了t.run()方法。在主线程中执行的一段代码 t.sta
线程时,没有实现可运行接口
另一方面,我知道实现Runnable
接口而不是扩展Thread
类是非常有意义的,但是就这个问题而言,假设我们扩展了Thread
类
让t
作为扩展Thread
类的实例,我有一个要在后台执行的代码块,它是在Thread
类的run()
方法中编写的
它使用t.start()
在后台完美运行,但我有点好奇,于是调用了t.run()
方法。在主线程中执行的一段代码
t.start()
做了什么t.run()
没有做什么?这就是类所做的。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();
}
这是预期的行为。t.start()
只是执行它所说的:启动一个新线程,执行run()
的代码部分t.run()
是从当前工作线程(在您的例子中是主线程)对对象的函数调用
请记住:只有在调用线程的start()
函数时,才会启动一个新线程,否则,调用它的函数(而不是start()
)与在任何其他对象上调用普通函数是一样的。t.start()
进行本机调用以实际执行运行()
新线程中的方法t.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();
}
现在,
另一方面,我知道实现Runnable接口比扩展Thread类更有意义
实际上,遵循这两种方法(实现Runnable或扩展线程)都非常有意义。这并不是说一个人在OO意义上是坏的。实现Runnable的好处是,您可以让您的类扩展另一个类(这实际上可能会破坏您的OO设计)。我相信您可以在这里找到答案:用足够简单的语言告诉您区别。差不多是t.start();正在制作/创建新线程,同时t.run();只是在主线上打电话哇,真棒的解释!谢谢你的回答。:)s/main-thread/current-thread/,AFAIK。我是针对当前上下文说话的。如果您计划将特性和功能添加到线程
,那么扩展线程
类是有意义的。如果您只想创建一个新线程,请实现Runnable
class.:)@DarkDust-我不明白你的意思。无论如何,实现Runnable的主要优点是,在这种情况下,你不是在扩展线程,因此你不会继承线程类的所有包袱,这可能是你无意中涉及的(调用/重写/变异)在您的实现代码中。当您想要创建一种新的线程对象时,扩展线程是有意义的。(例如,如果您想覆盖Thread.join()或Thread.setName())但是,Thread对象不是Thread:它是管理线程的对象。问:管理等待网络客户端的线程的对象与管理运行后台任务的线程的对象的职责是否不同?当然,线程本身有不同的职责,但是线程对象?。。。没那么多。谢谢你的回答。:)