Java多线程实现方式主要有三种:
一、继承Thread类
二、实现Runnable接口
三、使用ExecutorService、Callable、Future实现有返回结果的多线程。
其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。java
一、继承Thread类实现多线程
继承Thread类并复写run()方法。
其本质上也是实现了Runnable接口的一个实例,
它表明一个线程的实例,启动线程的方法就是经过Thread类的start()实例方法。
start()方法是一个native方法,它将启动一个新线程,并执行run()方法。
若是一个类继承了Thread类,那么一个对象就只能调用一次,若是调用屡次,则会抛出异常
例如:缓存
public class MyThread extends Thread { public void run() { System.out.println("MyThread.run()"); } } MyThread myThread1 = new MyThread(); myThread1.start();
重复启动报错:
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start( Thread.java:682 )多线程
二、实现Runnable接口方式实现多线程
实现一个Runnable接口并实现run()方法。
例如:并发
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();
JDK 源码:函数
public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } } private native void start0();
native:调用本机的操做系统函数this
三、使用ExecutorService、Callable、Future实现有返回结果的多线程-JDK1.5以上
ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。
Executor框架 详细能够参见:http://www.iteye.com/topic/366591
>>> 有返回值的任务必须实现Callable接口,
>>> 无返回值的任务必须Runnable接口。
JDK 源码:操作系统
<T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?> submit(Runnable task);
执行Callable任务后,能够获取一个Future的对象,
在该对象上调用get就能够获取到Callable任务返回的Object了,
再结合线程池接口ExecutorService就能够实现传说中有返回结果的多线程了
代码以下:
线程
import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * 有返回值的线程 */ @SuppressWarnings("unchecked") public class Test { @SuppressWarnings("rawtypes") public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("----程序开始运行----"); Date date1 = new Date(); int taskSize = 5; // 建立一个线程池 ExecutorService pool = Executors.newFixedThreadPool(taskSize); // 建立多个有返回值的任务 List<Future> list = new ArrayList<Future>(); for (int i = 0; i < taskSize; i++) { Callable c = new MyCallable(i + " "); // 执行任务并获取Future对象 Future f = pool.submit(c); // System.out.println(">>>" + f.get().toString()); list.add(f); } // 关闭线程池 pool.shutdown(); // 获取全部并发任务的运行结果 for (Future f : list) { // 从Future对象上获取任务的返回值,并输出到控制台 System.out.println(">>>>>>>>>=======" + f.get().toString()); } } } class MyCallable implements Callable<Object> { private String taskNum; MyCallable(String taskNum) { this.taskNum = taskNum; } public Object call() throws Exception { System.out.println(">>>" + taskNum + "任务启动"); Date dateTmp1 = new Date(); Thread.sleep(4000); Date dateTmp2 = new Date(); long time = dateTmp2.getTime() - dateTmp1.getTime(); System.out.println(">>>" + taskNum + "任务终止"); return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】"; } }
代码说明:
上述代码中Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。
一、 建立固定数目线程的线程池
=> public static ExecutorService newFixedThreadPool(int nThreads)
二、 建立一个可缓存的线程池
=> public static ExecutorService newCachedThreadPool()
调用execute 将重用之前构造的线程(若是线程可用)。
若是现有线程没有可用的,则建立一个新线程并添加到池中。
终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
三、建立一个单线程化的Executor
=> public static ExecutorService newSingleThreadExecutor()
四、建立一个支持定时及周期性的任务执行的线程池
=> public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
多数状况下可用来替代Timer类。code
ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。 若是Executor后台线程池尚未完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。