21xrx.com
2025-03-24 12:34:29 Monday
文章检索 我的文章 写文章
Java线程创建的三种方式
2023-06-17 17:59:32 深夜i     --     --
Java 线程 多线程编程

作为一个Java开发工程师,我深刻理解到多线程编程的重要性。在Java中,线程的创建方式有三种:继承Thread类、实现Runnable接口、实现Callable接口。下面我将为大家展示这三种方式的代码实例。

1. 继承Thread类

public class MyThread extends Thread {
  @Override
  public void run() {
    System.out.println("继承Thread类,实现多线程!");
  }
}
public class Main {
  public static void main(String[] args) {
    MyThread myThread = new MyThread();
    myThread.start();
  }
}

2. 实现Runnable接口

public class MyRunnable implements Runnable {
  @Override
  public void run() {
    System.out.println("实现Runnable接口,实现多线程!");
  }
}
public class Main {
  public static void main(String[] args) {
    MyRunnable myRunnable = new MyRunnable();
    Thread thread = new Thread(myRunnable);
    thread.start();
  }
}

3. 实现Callable接口

public class MyCallable implements Callable
  {
 
  @Override
  public String call() throws Exception
    return "实现Callable接口
}
public class Main {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
    MyCallable myCallable = new MyCallable();
    FutureTask
  futureTask = new FutureTask<>(myCallable);
 
    Thread thread = new Thread(futureTask);
    thread.start();
    String result = futureTask.get();
    System.out.println(result);
  }
}

以上就是Java线程创建的三种方式,分别是继承Thread类、实现Runnable接口、实现Callable接口。对于不同的场景,我们可以选择不同的方式来创建线程,从而实现多线程编程的目的。

  
  

评论区