Java实现多线程的三种方式

来源:互联网 发布:php开发app接口源码 编辑:程序博客网 时间:2024/06/06 15:52

1、Java实现多线程主要有三种方式:

  • (1)继承Thread类
  • (2)实现Runnable接口
  • (3)使用ExecutorService、Callable、Future实现有返回结果的多线程。

其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。

2、方式一:继承Thread类

Thread类本质上也是实现了Runnable接口的一个类,它代表一个线程的实例。

启动线程的唯一方法就是通过Thread类的start()方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。

通过自己的类直接extends Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。

//实现多线程方式一:继承Thread类public class MyThread extends Thread {    @Override    public void run() {        System.out.println("启动一个新线程, 并执行run()方法.");    }    public static void main(String[] args) {        MyThread myThread = new MyThread();        myThread.start();    }}

3、方式二:实现Runnable接口

如果自己的类已经extends另一个类,就无法直接extends Thread,此时,必须通过实现Runnable接口来创建线程。

public class Test {    public static void main(String[] args) {        Thread newThread = new Thread(new MyThread());        newThread.start();    }}class OtherClass {}//实现多线程方式二:实现Runnable接口class MyThread extends OtherClass implements Runnable {    @Override    public void run() {        System.out.println("创建线程, 并执行run()方法.");    }}

4、方式二:使用ExecutorService、Callable、Future实现有返回结果的多线程

需要开启新线程执行有返回值的任务必须实现Callable接口。

执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object结果了。

结合线程池接口ExecutorService就可以实现有返回结果的多线程了。

import java.util.concurrent.*;import java.util.Date;import java.util.List;import java.util.ArrayList;/** * 有返回值的线程 * @author Tao * */public class Test {    public static void main(String[] args) throws     InterruptedException, ExecutionException {        int poolSize = 10;  //线程池大小        //创建一个线程池        ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);        //创建多个Task        List<Future<Object>> futureList = new ArrayList<>();        for(int i = 0; i < poolSize; i++) {            Callable<Object> task = new MyTask("NO" + i);            //放入线程池中执行任务并取得返回值            Future<Object> future = threadPool.submit(task);            futureList.add(future);        }        //关闭线程池        threadPool.shutdown();        //输出所有结果        for(Future<Object> f : futureList) {            System.out.println(f.get().toString());        }    }}//定义任务类class MyTask implements Callable<Object> {    private String taskNum; //任务编号    public MyTask(String taskNum) {        this.taskNum = taskNum;    }    @Override    public Object call() throws Exception {        System.out.println("任务 " + taskNum + " 启动了...");        Date startTime = new Date();        Thread.sleep(1000);        Date endTime = new Date();        long costTime = endTime.getTime() - startTime.getTime();        System.out.println("任务 " + taskNum + " 执行完毕.");        //返回值        return taskNum + " 任务返回运行结果, 任务执行耗费时间【" + costTime + "毫秒】";    }}
原创粉丝点击