在Java中创建新线程有多少种方法?

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

有一种方法可以在Java中创建一个新线程,即实例化java.lang.Thread (实际运行该线程,您还需要调用start() )。

在Java代码中创建线程的所有其他东西都会回到封面后面的这一方面(例如, ThreadFactory实现将在某个时刻实例化Thread对象,……)。

有两种不同的方法可以指定在该Thread中运行的代码

  • 实现接口java.lang.Runnable并将实现它的类的实例传递给Thread构造函数 。
  • 扩展Thread本身并覆盖其run()方法。

第一种方法(实现Runnable )通常被认为是更正确的方法,因为您通常不会创建一个新的“类型”的Thread,而只是想在专用线程中运行一些代码(即Runnable )。

线程可以主要以3种不同的方式创建

  1. 扩展 java.lang。 线程类’
 class SampleThread extends Thread { //method where the thread execution will start public void run(){ //logic to execute in a thread } //let's see how to start the threads public static void main(String[] args){ Thread t1 = new SampleThread(); Thread t2 = new SampleThread(); t1.start(); //start the first thread. This calls the run() method. t2.start(); //this starts the 2nd thread. This calls the run() method. } } 
  1. 实现 java.lang。 Runnable接口
 class A implements Runnable{ @Override public void run() { // implement run method here } public static void main() { final A obj = new A(); Thread t1 = new Thread(new A()); t1.start(); } } 
  1. 实现 java.util.concurrent。 可调用的界面
 class Counter implements Callable { private static final int THREAD_POOL_SIZE = 2; // method where the thread execution takes place public String call() { return Thread.currentThread().getName() + " executing ..."; } public static void main(String[] args) throws InterruptedException, ExecutionException { // create a pool of 2 threads ExecutorService executor = Executors .newFixedThreadPool(THREAD_POOL_SIZE); Future future1 = executor.submit(new Counter()); Future future2 = executor.submit(new Counter()); System.out.println(Thread.currentThread().getName() + " executing ..."); //asynchronously get from the worker threads System.out.println(future1.get()); System.out.println(future2.get()); } } 

使用Executor框架的Callable接口进行线程池化。

Runnable或Callable接口比扩展Thread类更受欢迎

或者您可以创建一个Callable ,它是一个类似于Runnable的接口,除了它定义了一个可以返回值的方法调用 。 要实例化Callable,可以将其传递给执行程序。 您可以在此处找到有关multithreading和可调用示例的完整说明

在Java 6中启动线程的首选方法是使用Executors:

  ExecutorService es = Executors.newCachedThreadPool(); Runnable r = ; es.execute(r); 

实际上有四种方法可以在java中创建线程:

  1. 通过扩展java.lang.Thread
  2. 通过实现java.lang.Runnable接口
  3. 通过使用匿名内部类
  4. 通过实现Callable接口。

你已经提到过只有两种创建线程的方法,但第三种方法是调用线程。

在java1.5中,还有另一种调用线程的方法。 那是“ExecutorService”。 所有这些类都来自“java.util.concurrent”包。 使用“Executors”工厂类创建“ExecutorService”有多种方法。 以下是创建“ExecutorService”的方法之一..

ExecutorService es = Executors.newSingleThreadExecutor();

RunnableImpl r = new RunnableImpl();

未来fu = es.submit(r);

使用“ExecutorService”方法,我们可以将eighter Runnable或Callable提交给服务执行。

但是,这不能说是创建Thread的新方法。 这是因为ExecutorService在内部使用“ThreadFactory”类来创建一个内部使用eighter第一或第二种方法的新线程。 所以我们不得不说创建线程的方法只有两种,但java1.5中有一种新方法可以调用线程而不是创建线程。

对于创建线程,java中只有一种方法

即。 线程类start()方法但是有不同的方法通过使用不同的方式来运行线程

喜欢1.Thread 2.Runnable 3.RunnableFeature 4.Callable
5.ERxecutorService …等