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

2022-09-03 03:11:36

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


答案 1

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

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

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

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


答案 2

线程主要可以通过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。可运行接口

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());

    }
}

支持具有执行器框架的可调用接口,用于线程池。

可运行或可调用接口优先于扩展 Thread 类