【问题标题】:How many ways are for creating a new thread in Java?在 Java 中创建新线程有多少种方法?
【发布时间】:2018-05-29 14:32:22
【问题描述】:

其实,除了扩展Thread类和实现Runnable接口,还有什么其他的方法呢?

【问题讨论】:

  • 扩展 Thread 类不是一个好办法!总是使用后者
  • 基本上就是这样。还有其他方法可以执行 Runnables,如 ThreadPoolExecutor 等,但它们都需要实现 Runnable 接口。

标签: java multithreading


【解决方案1】:

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

在 Java 代码中创建线程的所有其他内容都回退到这种隐藏的方式(例如,ThreadFactory 实现将在某个时候实例化 Thread 对象,...)。

有两种不同的方式指定要在该线程中运行的代码

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

【讨论】:

  • 我很惊讶他们现在还没有弃用 Thread#run()。他们真的应该这样做。 Thread is Runnable 的想法是非常过时的,并且与 Thread 具有 可运行的想法相比具有相对限制性。其他类也是如此:“has a”通常比“is a”更强大。
  • @Joachim Sauer - callable 怎么样?它是否也回退到实例化 Thread 类?
  • @SantanuSahoo: CallableRunnable 非常相似,因为它本身不做任何与线程相关的事情,但它可以以各种方式用于传递代码以在某些情况下执行方式,包括在另一个线程中。因此,如果您将Callable 传递给您的ExecutorService,那么它很可能最终会在新线程上运行,但线程的实际实例化仍将通过new Thread 在幕后某处完成。
【解决方案2】:

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

  1. 扩展 java.lang.Thread 类'

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.可运行接口

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 类

【讨论】:

  • 认为在扩展线程时需要 Override,而不是在实现接口 Runnable 时。
【解决方案3】:

或者你可以创建一个Callable,它是一个类似于Runnable的接口,只是它定义了一个可以返回值的方法call。要实例化 Callable,您可以将其传递给执行程序。你可以找到多线程和可调用示例的完整解释here

【讨论】:

  • 实例化一个Callable,你可以使用Java的“new”操作符,就像你实例化任何其他对象一样。要使用一个可调用对象,您可以调用它的“Call()”方法,或者将它交给某个其他对象(例如,ExecutorService),它会在未来某个适当的时间为您调用它在某些适当的上下文中,也许在某些适当的线程中。
【解决方案4】:

在java中创建线程实际上总共有4种方法:

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

【讨论】:

  • 将线程实现到单独的其他类或作为匿名类只是使用它的一种方式。如上所述,实现线程的方式只有 3 种。
【解决方案5】:

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

    ExecutorService es = Executors.newCachedThreadPool();
    Runnable r = <your runnable here>;
    es.execute(r);

【讨论】:

  • 严格来说这是并发执行代码的首选方式。如果你真的想创建一个专门的Thread,那不是办法。
  • @Joachim 我认为在这里使用线程是可以的。注意线程中的小写 t。而这些执行者实际上是创建和管理线程。
  • @Gray 它有两种方法:execute(Runnable) 和另一个submit(Callable&lt;T&gt;)
  • @MisterSmith,如果要启动线程,请调用 Thread#start()。如果要运行 task,请使用执行器服务。 ExecutorService 可能会启动一个线程来运行您的任务,或者它可能会重用现有线程,或者它可能只是在调用线程中执行任务。 ExecutorService 接口只表示最终必须执行任务,并且您必须返回一个让您等待结果的 Future。除了执行任务之外,线程还有其他用途。
【解决方案6】:

您已经提到了创建线程的方法只有两种,但还有第三种方法可以调用线程。

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

ExecutorService es= Executors.newSingleThreadExecutor();

RunnableImpl r = new RunnableImpl();

未来 fu=es.submit(r);

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

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

【讨论】:

  • 同意,但 callable 仍然是另一种创建线程的方式。使用 Callable,您可以在完成后使用 future 从线程返回值,因此它肯定与可运行的不同,因此
【解决方案7】:

在java中创建线程只有一种方法

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

喜欢 1.Thread 2.可运行 3.RunnableFeature 4.可调用
5.ERexecutorService...等

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多