21xrx.com
2024-09-20 05:29:07 Friday
登录
文章检索 我的文章 写文章
Java线程创建的三种模式
2023-06-15 19:14:56 深夜i     --     --
Java线程 继承Thread类 实现Runnable接口 实现Callable接口

我一直对多线程编程很感兴趣,最近我学到了Java线程的创建方式,Java线程可以通过三种不同的模式来创建:继承Thread类、实现Runnable接口、实现Callable接口并使用FutureTask包装器。

继承Thread类是最简单的线程创建方式之一。我们可以创建一个继承Thread类的子类,并重写run()方法来执行线程的代码。例如:


public class MyThread extends Thread {

  public void run() {

    System.out.println("Hello from MyThread!");

  }

}

public class Main {

  public static void main(String[] args) {

    MyThread thread = new MyThread();

    thread.start(); // 启动线程

  }

}

实现Runnable接口是另一种线程创建方式。我们定义一个实现了Runnable接口的类,并重写run()方法来执行线程的代码。例如:


public class MyRunnable implements Runnable {

  public void run() {

    System.out.println("Hello from MyRunnable!");

  }

}

public class Main {

  public static void main(String[] args) {

    MyRunnable runnable = new MyRunnable();

    Thread thread = new Thread(runnable);

    thread.start(); // 启动线程

  }

}

实现Callable接口并使用FutureTask包装器是第三种线程创建方式。Callable接口类似于Runnable接口,不同之处在于它可以返回结果并抛出异常。FutureTask可以包装一个Callable实现,并且可以在执行时异步获取结果。例如:


public class MyCallable implements Callable {

  public Integer call() throws Exception {

    System.out.println("Hello from MyCallable!");

    return 123;

  }

}

public class Main {

  public static void main(String[] args) throws Exception {

    MyCallable callable = new MyCallable();

    FutureTask futureTask = new FutureTask<>(callable);

    Thread thread = new Thread(futureTask);

    thread.start(); // 启动线程

    int result = futureTask.get(); // 获取结果

    System.out.println("Result: " + result);

  }

}

以上是Java线程的三种创建模式,每种方式都有其优缺点,需要根据具体应用情况选择合适的方式。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复