21xrx.com
2025-03-30 13:36:37 Sunday
文章检索 我的文章 写文章
Java多线程编程的三种创建方式
2023-06-11 06:49:13 深夜i     10     0
Java线程 继承Thread类 实现Runnable接口 实现Callable接口

Java线程的创建方式有几种

作为一个Java开发者,多线程编程是必备的技能之一。而线程的创建方式也是优化和调整应用程序性能的关键因素。下面我会简述Java中线程的创建方式有哪些,并给出相应的代码例子。

1. 继承Thread类

这是Java最基本的线程创建方式,我们只需要继承Thread类并重写其run()方法即可创建线程。

下面是关键代码:

public class MyThread extends Thread {
  @Override
  public void run()
    // do something here
  
}
// 在主函数中创建线程
public static void main(String[] args) {
  MyThread thread = new MyThread();
  thread.start();
}

2. 实现Runnable接口

这种方式比继承Thread类更为灵活,因为一个类可以继承其他类但只能继承一个Thread类。实现Runnable接口后,我们同样需要重写其中的run()方法。

关键代码如下:

public class MyRunnable implements Runnable {
  @Override
  public void run()
    // do something here
  
}
// 在主函数中创建线程
public static void main(String[] args) {
  MyRunnable runnable = new MyRunnable();
  Thread thread = new Thread(runnable);
  thread.start();
}

3. 实现Callable接口

Callable接口和Runnable接口的作用类似,不同之处在于,Callable接口的call()方法可以返回执行的结果或抛出异常。与Runnable接口不同,它支持泛型返回值,以便在执行任务后返回类型安全的结果。

代码示例如下:

public class MyCallable implements Callable
  {
 
  @Override
  public Integer call()
    // do something here and return a result
  
}
// 在主函数中创建线程
public static void main(String[] args) {
  MyCallable callable = new MyCallable();
  FutureTask
  result = new FutureTask<>(callable);
 
  Thread thread = new Thread(result);
  thread.start();
  try {
    Integer res = result.get();
    // process the result here
  } catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
  }
}

以上是Java线程的三种创建方式,每一种方式都有其独特的优劣点,开发者需根据实际场景灵活选择合适的创建方式。

  
  

评论区

请求出错了