【转载】线程创建的三种方式

参考

  1. https://www.bilibili.com/video/BV1V4411p7EF?p=9&spm_id_from=pageDriver
  2. https://blog.csdn.net/Hubz131/article/details/103096867
  3. https://blog.csdn.net/zhuchunyan_aijia/article/details/121756472
  4. https://blog.csdn.net/qq_40270751/article/details/78843226

介绍

  1. 继承 Thread 类,并重写 run 方法,没有返回值。
  2. 实现 Runnable 接口,并重写 run 方法(还是通过Thread实现的多线程),支持实现多个类,没有返回值。
  3. 实现 Callable 接口,并重写 call 方法,有返回值,可以通过线程池调用及 Thread 执行。

示例代码

  1. 继承 Thread
package thread;

/**
 * 继承 Thread 类并重写run方法
 * @Author 夏秋初
 * @Date 2022/2/21 21:32
 */
public class TestThread extends Thread{
    @Override
    public void run(){
        System.out.println(Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        TestThread testThread0 = new TestThread();
        testThread0.setName("0");
        TestThread testThread1 = new TestThread();
        testThread1.setName("1");
        TestThread testThread2 = new TestThread();
        testThread2.setName("2");
        testThread0.start();
        testThread1.start();
        testThread2.start();

    }
}

  1. 实现 Runnable
package thread;

/**
 * @Author 夏秋初
 * @Date 2022/2/21 21:38
 */
public class TestRunnable implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread thread0 = new Thread(new TestRunnable(), "0");
        Thread thread1 = new Thread(new TestRunnable(), "1");
        Thread thread2 = new Thread(new TestRunnable(), "2");
        thread0.start();
        thread1.start();
        thread2.start();
    }

}

  1. 实现 Callable
package thread;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.*;

/**
 * @Author 夏秋初
 * @Date 2022/2/21 21:45
 */
public class TestCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        return Thread.currentThread().getName();
    }

    public static void main(String[] args) throws InterruptedException,ExecutionException  {
        TestCallable testCallable = new TestCallable();
        // 不使用线程池
        FutureTask<String> futureTask = new FutureTask<String>(testCallable);
        //
        new Thread(futureTask, "不使用线程池获取线程执行结果").start();
        //
        System.out.println(futureTask.get());

        //
        System.out.println("======");

        // 使用线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        //
        Set<Future<String>> arrayList = new HashSet<>(10);
        //
        for (int i = 0; i < 10; i++) {
            Future<String> future = executorService.submit(testCallable);
            arrayList.add(future);
        }
        //
        executorService.shutdown();

        arrayList.forEach(item->{
            try {
                System.out.println(item.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}

posted @   夏秋初  阅读(30)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示