0、概述:
继承Thread类,实现Runnable接口,实现Callable接口通过FutureTask包装器来创建Thread线程,使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式执行完没有返回值,后两种是有返回值。(其实我想说,真正实现多线程的方法也就Runnable这一种,其他的都是换了一个皮肤)
1、继承Thread类创建线程
Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例。通过继承 Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。如:
class MyThread extends Thread{
private String name ;
public MyThread(String name ) {
this.name = name ;
}
public void run() {
System.out.println("我是线程:"+this.name);
}
}
public class Test{
public static void main(String args[]) {
MyThread my1 = new MyThread ("线程一") ;
MyThread my2 = new MyThread ("线程二") ;
my1.start();
my2.start();
}
}
2、实现Runnable接口创建线程
如果自己的类已经extends另一个类,就无法直接extends Thread,此时可以实现一个Runnable接口,不过 启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例 ,如:
class MyThread implements Runnable{
private String name ;
public MyThread(String name ) {
this.name = name ;
}
public void run() {
System.out.println("我是线程:"+this.name);
}
}
public class Test{
public static void main(String args[]) {
MyThread my1 = new MyThread ("线程一") ;
MyThread my2 = new MyThread ("线程二") ;
new Thread(my1).start(); //实现接口没有start()方法,所以需要使用Thread类的匿名对象来调用start()方法
new Thread(my2).start();
}
}
3、实现Callable接口通过FutureTask包装器来创建Thread线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread implements Callable<String>{
public String call()throws Exception {
return "我是被传出去的数据";
}
}
public class Test{
public static void main(String args[]) throws InterruptedException, ExecutionException {
MyThread my1 = new MyThread();
FutureTask<String> task1 = new FutureTask<String>(my1);
new Thread(task1).start();
System.out.println("结果:"+ task1.get());
}
}
4、使用ExecutorService、Callable、Future实现有返回结果的线程
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadTest {
public static void main(String[] args) {
//创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(5);
//创建数据,用于保存返回对象
List<Future<Object>> futureList= new ArrayList<>();
for (int i = 0; i <5; i++) {
//创建任务
Callable<Object> task = new TestCallable("任务"+i);
//提交任务,获取返回对象
Future<Object> f = threadPool.submit(task);
//将结果对象保存到数组
futureList.add(f);
}
//关闭线程池
threadPool.shutdown();
//打印任务返回值
for (Future<Object> future : futureList) {
try {
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class TestCallable implements Callable<Object>{
private String name;
TestCallable(String name){
this.name=name;
}
@Override
public Object call() throws Exception {
return name;
}
}
参考博客: