上海奉贤做网站,自己建网站要学什么,安徽网站建设方案优化,wordpress左侧目录主题多线程的创建和启动方式
在Java中#xff0c;创建多线程主要有以下三种方式#xff1a;
继承Thread类实现Runnable接口使用Callable接口与Future
下面是这三种方式的简单示例#xff0c;以及如何在主类中启动它们。
1. 继承Thread类
class MyThread extends Thread {Ov…多线程的创建和启动方式
在Java中创建多线程主要有以下三种方式
继承Thread类实现Runnable接口使用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 CallableString {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();FutureTaskString 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类启动。
这样你就可以通过这三种方式创建和启动多线程了。