Java中常见的线程创建方式

73 阅读2分钟

常见的Java线程的创建方式

  • 继承Thread
  • 实现Runnable接口
  • 通过ExecutorServiceCallable<Class>实现有返回值的线程
  • 基于线程池

(1)继承Thread类:

public class ThreadDemo extends Thread{
    @Override
    public void run() {
        System.out.println("create a thread:"+Thread.currentThread().getName());
    }
    public static void main(String[] args) {
        ThreadDemo thread = new ThreadDemo();
        thread.start();
    }
}

(2)实现Runnable接口:

public class RunnableDemo implements Runnable{

    @Override
    public void run() {
        System.out.println("create by implements Runnable");
    }

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

或者利用函数式编程:

new Thread(()->{
 System.out.println("create by implements Runnable");
}).start();

(3)通过ExecutorServiceCallable<Class>实现有返回值的线程

有时我们需要在主线程中开启多个子线程并发执行一个任务,然后收集各个线程返回的结果并将最终结果汇总起来,这时就需要用到Callable接口。

//1、通过实现Callable接口创建MyCallable线程
public class MyCallable implements Callable<String> {

    private String name;
    //通过构造函数为线程传递参数,以定义线程的名称
    public MyCallable(String name){
        this.name=name;
    }
    @Override
    public String call() throws Exception {
        return name;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //2、创建一个固定大小为5的线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //3、创建多个有返回值的任务列表list
        List<Future> list=new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            //4、创建一个有返回值的线程实例
            MyCallable c = new MyCallable(i + " ");
            //5、提交线程,获取Future对象并将其保存到Future List中
            Future<String> future = pool.submit(c);
            System.out.println("submit a callable thread:"+i);
            list.add(future);
        }
        //6、关闭线程池,等待线程执行结束
        pool.shutdown();
        //7、遍历所有线程的运行结果
        for (Future future : list) {
            //从Future对象上获取任务的返回值,并将结果输出到控制台
            System.out.println("get the result from callable thread:"+ future.get().toString());
        }
    }
}

image-20230822123154811

(4)基于线程池

通过Executors工厂方法创建

//创建大小为10的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
//提交多个线程任务并执行
for (int i = 0; i < 10; i++) {
    threadPool.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" is running");
        }
    });
}

或者new ThreadPoolExecutor

//通过ThreadPoolExecutor构造函数自定义参数创建线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(10,   //核心线程数
        20,                             //最大线程数
        1L,
        TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(100),	//任务队列
        new ThreadPoolExecutor.CallerRunsPolicy());//拒绝策略
for (int i = 0; i < 10; i++) {
    //执行Runnable
    executor.execute(()->{
        System.out.println(Thread.currentThread().getName()+" is running");
    });
}
//终止线程池
executor.shutdown();
while(!executor.isTerminated()){}
System.out.println("Finished all threads");