欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 在Java中创建多线程的三种方式

在Java中创建多线程的三种方式

2025/5/8 2:52:46 来源:https://blog.csdn.net/weixin_47121832/article/details/143031243  浏览:    关键词:在Java中创建多线程的三种方式

多线程的创建和启动方式

在Java中,创建多线程主要有以下三种方式:

  1. 继承Thread类
  2. 实现Runnable接口
  3. 使用Callable接口与Future

下面是这三种方式的简单示例,以及如何在主类中启动它们。

1. 继承Thread类

class MyThread extends Thread {@Overridepublic void run() {System.out.println("Thread using inheritance from Thread class.");}
}

2. 实现Runnable接口

class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("Thread using Runnable interface.");}
}

3. 使用Callable接口与Future

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception {return "Thread using Callable interface.";}
}

主类用来启动线程

public class Main {public static void main(String[] args) {// 启动继承Thread类的线程MyThread thread1 = new MyThread();thread1.start();// 启动实现Runnable接口的线程Thread thread2 = new Thread(new MyRunnable());thread2.start();// 启动使用Callable接口的线程MyCallable myCallable = new MyCallable();FutureTask<String> futureTask = new FutureTask<>(myCallable);Thread thread3 = new Thread(futureTask);thread3.start();// 获取Callable线程的返回值try {String result = futureTask.get();System.out.println(result);} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}
}

总结

  • 使用Thread类时,创建一个子类,重写run方法。
  • 使用Runnable接口时,实现Runnable接口,定义run方法,再通过Thread类启动。
  • 使用Callable接口时,创建实现Callable的类,使用FutureTask来处理返回值,依然通过Thread类启动。

这样,你就可以通过这三种方式创建和启动多线程了。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词