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

Ion*_*scu 14 java multithreading

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

Joa*_*uer 33

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

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

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

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


ank*_*249 21

线程可以主要以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.  
    }
} 
Run Code Online (Sandbox Code Playgroud)
  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();
    }


}
Run Code Online (Sandbox Code Playgroud)
  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());

    }
}
Run Code Online (Sandbox Code Playgroud)

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

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


Dim*_*tri 5

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