📚 分类
多线程
🕵🏽‍♀️ 问题描述
创建线程的方式有哪些?
👨‍🏫 问题讲解
❒ 共有四种方式可以创建线程,分别是:

✔ 继承Thread类

public class MyThread extends Thread {
  @Override
  public void run() {
    System.out.printin("MyThread...run...");
  }
  public static void main(String[] args){
    //创建MyThread对象
    MyThread t1 = new MyThread():
    MyThread t2= new MyThread();
    // 调用start方法启动线程
    t1.start():
    t2.start():
  }
}

✔ 实现runnable接口

public class MyRunnable implements Runnable{
  @Override
  public void run() {
    System.out.println("MyRunnable...run...");
  }
  public static void main(String[] args) {
    //创建MyRunnable对象
    MyRunnable mr = new MyRunnable():
    // 创建Thread对象
    Thread t1 = new Thread(mr);
    Thread t2 = new Thread(mr);
    // 调用start方法启动线程
    t1.start();
    t2.start();
  }
}

✔ 实现Callable接口

public class MyCallable implements Callable<String>{
  @Override
  public String call() throws Exception {
    System.out.println(Thread.currentThread().getName());
    return "ok";
  }
  public static void main(String[] args) throws ExecutionException,InterruptedException{
    /创建MyCallable对象
    MyCallable mc = new MyCallable():
    // 创建FutureTask
    FutureTask<String> ft = new FutureTask<String>(mc);
    // 创建Thread对象
    Thread t1 = new Thread(ft);
    Thread t2 = new Thread(ft);
    // 调用start方法启动线程
    t1.start();
    // 调用ft的get方法获取执行结果
    String result =ft.get():
    //输出
    System.out.printin(result);
  }
}

✔ 线程池创建线程

public class MyExecutors implements Runnable{
  @Override
  public void run() {
    System.out.println("MyRunnable...run...");
  }
  public static void main(String[] args){
    //创建线程池对象
    ExecutorService threadPool = Executors.newFixedThreadPool(3);
    threadPool.submit(new MyExecutors()) ;
    //关闭线程池
    threadPool.shutdown();
  }
}
🏳️‍🌈 问题总结
❒ 共有四种方式可以创建线程,分别是:

✔ 继承Thread类
✔ 实现runnable接口
✔ 实现Callable接口
✔ 线程池创建线程
📖 问题信息
📈 浏览次数:10 | 📅 更新时间:2025-12-01 22:02:15
📦 创建信息
🏷️ ID:97 | 📅 创建时间:2024-12-12 08:54:19