java多线程 三种实现方式

java多线程 三种实现方式

java多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种Callable是带返回值的,返回结果可以从Future中取出来

1.继承Thread类

继承Thread类的方法尽管被我列为一种实现多线程的方式,但Thread本质上也是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这方式种实现多线程很简单,通过自己的类直接extends Thread,并覆写run()方法,就可以启动新线程并执行自己定义的run()方法。例如:

public class MyThread extends Thread {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}

在合适的地方启动线程,如下:

MyThread myThread1 = new MyThread();  
MyThread myThread2 = new MyThread();  
myThread1.start();  
myThread2.start();

2.实现Runnable接口

如果自己的类已经extends另一个类,就无法直接extends Thread,此时必须实现一个Runnable接口,如下:

public class MyThread extends OtherClass implements Runnable {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}

为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例:

MyThread myThread = new MyThread();  
Thread thread = new Thread(myThread);  
thread.start();

事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run(),参考JDK源代码:

public void run() {  
  if (target != null) {  
   target.run();  
  }  
}

3.使用ExecutorService、Callable

ExecutorService、Callable这个对象实际上都是属于Executor框架中的功能类。返回结果的线程是在JDK1.5中引入的新特征。返回值的任务必须实现Callable接口,类似的,无返回值的任务必须实现Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到CallAble任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中的有返回结果的多线程。下面提供了一个完整的有返回结果的多线程测试例子,在JDK1.8下验证过没问题可以直接使用。代码如下:

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 有返回值的多线程
 *
 * @author haohj
 * @date 2020-04-28 14:47
 */
public class Demo3 {
    public static void main(String[] args) {
        System.out.println("-----程序开始运行------");
        LocalDateTime startTime = LocalDateTime.now();

        int taskSize = 5;

        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(taskSize);

        // 创建多个有返回值的任务
        List<Future> futureList = new ArrayList<>();
        for (int i = 0; i < taskSize; i++) {
            Callable c = new MyCallable(i + " ");
            // 执行任务并获取Future对象
            Future future = executorService.submit(c);
            futureList.add(future);
        }

        // 关闭线程池
        executorService.shutdown();

        // 获取所有并发任务的运行结果
        futureList.forEach(future -> {
            try {
                System.out.println(">>>" + future.get().toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        LocalDateTime endTime = LocalDateTime.now();
        Duration duration = Duration.between(startTime,endTime);
        System.out.println("----程序结束运行----,程序运行时间【"
                + duration.toMillis() + "毫秒】");
    }

    public static class MyCallable implements Callable<Object> {
        private String taskNum;

        public MyCallable(String taskNum) {
            this.taskNum = taskNum;
        }

        @Override
        public Object call() throws Exception {
            System.out.println(">>>" + taskNum + "任务启动");
            LocalDateTime dateTmp1 = LocalDateTime.now();
            Thread.sleep(1000);
            LocalDateTime dateTmp2 = LocalDateTime.now();
            Duration duration = Duration.between(dateTmp1,dateTmp2);
            System.out.println(">>>" + taskNum + "任务终止");
            return taskNum + "任务返回运行结果,当前任务时间【" + duration.toMillis() + "毫秒】";
        }
    }
}

代码说明:

上述代码中Executors类,提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口。

public static ExecutorService newFixedThreadPool(int nThreads)

创建固定数目线程的线程池。

public static ExecutorService newCachedThreadPool()

创建一个可缓存的线程池,调用execute将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有60秒钟未被使用的线程。

public static ExecutorService newSingleThreadExecutor()

创建一个单线程化的Executor。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)

创建一个支持定时及周期性的任务执行线程池,多数情况下可用来代替Timer类。

ExecutorService提供了submit()方法,传递一个Callable或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,则调用返回Future对象的get()方法会阻塞,直到计算完成。

Thread和Runnable的区别和联系

如果研究一下源代码就会发现:Thread类其实本身就是实现了Runnable接口的一个类。

因此Thread类中的方法和成员变量要比Runnable多,最典型的就是Thread有start()方法,但是Runnable接口没有start()方法。

如果想要执行一段线程:

 public threadTest extends Thread {...
@Override
public void run() {..}
}

threadTest th1=new threadTest("一号窗口");     
th1.start();

这里继承了Thread类,并重写了方法run()。

然后调用此类的start()方法来执行,记住不是调用run()方法,而是start()方法,因为:

  • run()并不是启动线程,而是简单的方法调用。
  • 并不是一启动线程(调用start()方法)就执行这个线程,而是进入就绪状态,什么时候执行还要看CPU。

区别

实际开发中我们通常采用Runnable接口来实现多线程。因为实现Runnable接口比继承Thread类有如下好处:

  • 避免继承的局限,一个类可以实现多个接口,但是类智能继承一个类。
  • Runnable接口实现的线程便于资源共享。而且通过Thread类实现,各自线程的资源是独立的,不方便共享。

联系

public class Thread extends Object implements Runnable

查看源码发现Thread类也是Runnable接口的实现类。

针对区别的第二条:Runnable接口实现的多线程便于资源共享;而通过继承Thread类实现,各自线程的资源是独立的,不方便共享。

举个例子:

(1)继承Thread类:

/**
 * 通过继承Thread类实现多线程
 * Thread类是有run()方法的
 * 也有start方法
 *
 * @author haohj
 * @date 2020-04-28 16:46
 */
public class ThreadTest extends Thread {
    private int ticket = 10;
    private String name;

    public ThreadTest(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        //super.run();
        while (true) {
            if (this.ticket > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(this.name + "卖票--->" + (this.ticket--));
            } else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        ThreadTest th1 = new ThreadTest("一号窗口");
        ThreadTest th2 = new ThreadTest("二号窗口");
        th1.start();
        th2.start();
    }
}

(2)实现Runnable接口:

/**
 * 通过实现Runnable接口,实现多线程
 * Runnable类是有run()方法的
 * 但是没有start方法
 *
 * @author haohj
 * @date 2020-04-28 16:56
 */
public class RunnableTest implements Runnable {
    private int ticket = 10;

    @Override
    public void run() {
        while (true) {
            if (this.ticket > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖票--->" + (this.ticket--));
            } else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        RunnableTest mt = new RunnableTest();
        Thread t1 = new Thread(mt, "一号窗口");
        Thread t2 = new Thread(mt, "二号窗口");
        t1.start();
        t2.start();
    }
}

可以看到:Thread 各线程资源是独立的,Runnable 便于实现线程共享资源

RunNable、Callable、Future的区别与联系

Runable Callable Future都是我们在java多线程开发中遇到的接口,那么这些接口之间有什么区别呢?

Runable

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

作为我们多线程开发中经常使用到的接口,它定义run方法,只要对象实现这个方法,将对象作为参数传入到new Thread(Runnable A),线程一旦start(),那么就自动执行了,没有任何的返回结果,无法知道什么时候结束,适用于完全异步的任务,不用关心结果。例如:

Thread a = new Thread(()->System.out.println("hello word"));
a.start();

CallAble

package java.util.concurrent;

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}

Callable定义的接口call(),它能够抛出异常,并且能够有一个返回结果。实现了Callable要想提交到线程池中,直接通过executorService.submit(new CallAbleTask()),但是返回的结果是Future,结果信息从Future里面取出,具体的业务逻辑在call中执行。

public void funA() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> futureList = new ArrayList<>();

        //创建10个任务并执行
        for (int i = 0; i < 10; i++) {
            //使用executorService执行Callable类型的任务,并且将结果保存在Future中
            Future<String> future = executorService.submit(new CallAbleTask(i));
            //将任务执行结果存到list中
            futureList.add(future);
        }
    }

    public class CallAbleTask implements Callable<String> {
        private int id;

        public CallAbleTask(int id) {
            this.id = id;
        }

        @Override
        public String call() throws Exception {
            System.out.println("call方法被自动调用,开始干活  " + Thread.currentThread().getName());
            Thread.sleep(1000);
            return "返回" + id + "---" + Thread.currentThread().getName();
        }
    }

Future提供了五个接口,功能入下图:

public interface Future<V> {
    //用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false
	boolean cancel(boolean mayInterruptIfRunning);
    //表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回true
	boolean isCancelled();
    //表示任务是否已经完成,若任务完成,则返回true
	boolean isDone();
    //用来获取执行结果,这个方法会产生阻塞会一直等到任务执行完毕才返回
	V get() throws InterruptedException, ExecutionException;
    //用来获取执行结果,入岗在指定时间内,还没有获取到结果,就直接返回null
	V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

总的来说Future能够控制Callable对象的执行,检测是否做完,可以阻塞式获取结果,也可以等待一段时间内获取结果。

ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> futureList = new ArrayList<>();

        //创建10个任务并执行
        for (int i = 0; i < 10; i++) {
            //使用executorService执行Callable类型的任务,并且将结果保存在Future中
            Future<String> future = executorService.submit(new CallAbleTask(i));
            //将任务执行结果存到list中
            futureList.add(future);
        }

        futureList.forEach(future-> {
            try {
                System.out.println(future.get()+"执行结果");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

我们能够看到方法的执行都是Callable,但是最后获取结果通过Future,get的方式的话,就是一直会阻塞在那里获取。

以上总结:

  • Runnable适用于完全异步的任务,不用操心执行情况,异常出错的
  • Callable适用于需要返回结果的,对执行中的异常要知晓的,需要提交到线程池中
  • Future主要是线程池执行Callable任务返回的结果。它能够中断任务的执行,一直等待结果,或者等待一段时间获取结果。

参考:Runable Callable Future 的区别与联系

参考:Java中继承thread类与实现Runnable接口的区别

参考:Runable和thread的区别(多线程必须用Runable)

参考:JAVA多线程实现和应用总结

posted @ 2020-04-29 09:24  名字不知道起什么好呢  阅读(396)  评论(0编辑  收藏  举报