@nalan90
2017-09-08T01:18:35.000000Z
字数 5165
阅读 858
Java
线程的生存周期

线程的实现
线程相关类常用方法
示例代码
## extends Thread classclass MyThread extends Thread {private String name;public MyThread(String name) {this.name = name;}public void run() {System.out.println("Thread name:" + this.name + " Thread ID:" + Thread.currentThread().getId());}}public class Demo02 {public static void main(String args[]) {System.out.println("Main thread ID:" + Thread.currentThread().getId());MyThread t1 = new MyThread("thread1");t1.start();MyThread t2 = new MyThread("thread2");t2.start();}}## 运行结果Main thread ID:1Thread name:thread1 Thread ID:10Thread name:thread2 Thread ID:11----------## implements Runnable interfaceclass MyRunnable implements Runnable {public void run() {System.out.println("Thread ID:" + Thread.currentThread().getId());}}public class Demo03 {public static void main(String args[]) {System.out.println("Main thread ID:" + Thread.currentThread().getId());MyRunnable run = new MyRunnable();Thread t = new Thread(run);t.start();}}## 运行结果Main thread ID:1Thread ID:10
使用ExecutorService、Callable、Future实现有返回结果的多线程
ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。
常用方法如下:
示例代码
package com.jiudouyu.thread;import java.util.concurrent.*;import java.util.*;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(1000);Date dateTmp2 = new Date();long time = dateTmp2.getTime() - dateTmp1.getTime();System.out.println(">>>" + taskNum + "任务终止");return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";}}public class Demo04 {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());}Date date2 = new Date();System.out.println("----程序结束运行----,程序运行时间【"+ (date2.getTime() - date1.getTime()) + "毫秒】");}}## 运行结果----程序开始运行---->>>0 任务启动>>>1 任务启动>>>2 任务启动>>>3 任务启动>>>4 任务启动>>>0 任务终止>>>0 任务返回运行结果,当前任务时间【1000毫秒】>>>2 任务终止>>>3 任务终止>>>1 任务终止>>>1 任务返回运行结果,当前任务时间【1001毫秒】>>>2 任务返回运行结果,当前任务时间【1001毫秒】>>>3 任务返回运行结果,当前任务时间【1000毫秒】>>>4 任务终止>>>4 任务返回运行结果,当前任务时间【1002毫秒】----程序结束运行----,程序运行时间【1010毫秒】