本文介绍了在Java中创建新线程有多少种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,除了扩展Thread类和实现Runnable接口之外还有哪些其他方法?

Actually, what other ways are available apart from extending the Thread class and implementing the Runnable interface?

推荐答案

确切地说一种在Java中创建新线程的方法,即实例化(实际运行该线程你还需要调用 start())。

There is exactly one way to create a new thread in Java and that is to instantiate java.lang.Thread (to actually run that thread you also need to call start()).

在Java代码中创建线程的其他所有内容都会回到封面后面的这一方面(例如实现将实例化线程某些时候的对象,......)。

Everything else that creates threads in Java code falls back to this one way behind the cover (e.g. a ThreadFactory implementation will instantiate Thread objects at some point, ...).

指定运行哪些代码有两种不同的方法在该线程中:


  • 实现接口并将实现它的类的实例传递给。

  • 扩展线程本身并覆盖其方法。

  • Implement the interface java.lang.Runnable and pass an instance of the class implementing it to the Thread constructor.
  • Extend Thread itself and override its run() method.

第一种方法(实现 Runnable )通常被认为是更正确的方法,因为你通常不会创建新的善待线程,但只是想运行一些代码(即一个专用线程中的 Runnable )。

The first approach (implementing Runnable) is usually considered the more correct approach because you don't usually create a new "kind" of Thread, but simply want to run some code (i.e. a Runnable) in a dedicated thread.

这篇关于在Java中创建新线程有多少种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:52