创建线程的常见方式

一、继承Thread类

继承Thread类重写run()方法。

public class myThread extends  Thread{
    @Override
    public void run(){
        System.out.println("线程启动了");
    }

    public static void main(String[] args) {
        myThread myThread = new myThread();
        myThread.start();
    }
}

特点

  • 简单

二、实现Runnable接口

实现 Runnable 接口的 run() 方法,并将实例交给 Thread 类。

public class MyThread1 implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程启动了" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MyThread1 myThread1 = new MyThread1();
        Thread thread = new Thread(myThread1);
        thread.start();
    }
}

特点

  • 解耦任务与线程,可复用同一个 Runnable 对象。

三、实现 Callable 接口 + FutureTask

实现 Callable 接口(可返回结果和抛出异常),结合 FutureTask 获取返回值。

public class MyThread2 implements Callable<String> {
   @Override
   public String call() throws Exception {
       return "线程启动";
   }

   public static void main(String[] args) throws ExecutionException, InterruptedException {
       MyThread2 myThread2 = new MyThread2();
       FutureTask<String> futureTask = new FutureTask<>(myThread2);
       Thread thread = new Thread(futureTask);
       thread.start();
       System.out.println(futureTask.get());
   }
}

特点

  • 支持返回值、异常处理。
  • 适合需要异步计算结果的场景。

四、使用线程池

通过线程池(如 ExecutorService)管理线程,避免频繁创建销毁开销。
通用代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        // 创建固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // 提交Runnable任务
        executor.execute(() -> {
            System.out.println("线程池执行任务(Runnable)");
        });

        // 提交Callable任务(通过submit获取Future)
        executor.submit(() -> "Callable结果");

        executor.shutdown(); // 关闭线程池
    }
}

一个例子:

public class ThreadPool {
    public static void main(String[] args) {
        int corePoolSize = 5;
        int maxPoolSize = 10;
        long keepAliveTime = 10;
        TimeUnit unit = TimeUnit.SECONDS;
        ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(10);
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        };
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        for (int i = 0; i < 30; i++){
            threadPoolExecutor.execute(new MyThread1());
            System.out.println("线程池中线程数目:"+threadPoolExecutor.getPoolSize()+",队列中等待执行的任务数目:"+
                    threadPoolExecutor.getQueue().size()+",已执行完成的任务数目:"+threadPoolExecutor.getCompletedTaskCount());
        }
        //threadPoolExecutor.shutdown();
    }
}

特点

  • 资源复用:减少线程创建/销毁开销。
  • 统一管理:支持任务队列、线程数控制、返回值获取(submit)。
  • 生产环境首选。

你可能感兴趣的:(java,开发语言)