创建线程的三种方式
一、继承Thread类
java中类是单继承的,继承了该类就无法继承其他类,增加了代码的耦合度,现在提倡的是面向接口编程。
二、实现Runnable接口
相比与方式一,使用实现接口来实现,降低了程序间的耦合度,缺点是没有返回值。
三、实现Callable接口,将Callable实例传给FutureTask(FutureTask实现了RunnableFuture接口,RunnableFuture继承了Runnable接口)
和方式二一样也是通过实现接口来创建线程,不同的是可以有返回值。
代码:
1 package com.shamgod.thread; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.ExecutorService; 6 import java.util.concurrent.Executors; 7 import java.util.concurrent.Future; 8 import java.util.concurrent.FutureTask; 9 10 /** 11 * 创建线程的三种方式 12 * @author ShammGod 13 * 14 */ 15 public class TestThread { 16 17 public static void main(String[] args) throws InterruptedException, ExecutionException { 18 //继承Thread类 19 Thread t1 = new Thread1(); 20 t1.start(); 21 22 //实现Runnable接口,将该实例作为参数创建Thread对象 23 Runnable runnable = new Thread2(); 24 Thread t2 = new Thread(runnable); 25 t2.start(); 26 27 //实现Callable接口,将该实例作为参数创建FutureTask对象,将FutureTask对象作为参数创建Thread对象 28 Callable callable = new Thread3(); 29 FutureTask<String> futureTask = new FutureTask<>(callable); 30 Thread t3 = new Thread(futureTask); 31 t3.start(); 32 futureTask.get();//call方法的返回值 33 34 //实现Callable接口,将该实例传给线程池的submit方法启动线程 35 ExecutorService threadPool = Executors.newCachedThreadPool(); 36 Callable<String> task = new Thread3(); 37 Future<String> future = threadPool.submit(task); 38 threadPool.shutdown(); 39 future.get();//call方法的返回值 40 41 } 42 } 43 /** 44 * 1、继承Thread 45 * @author ShammGod 46 * 47 */ 48 class Thread1 extends Thread{ 49 @Override 50 public void run() { 51 System.out.println("我是继承Thread创建的线程:" + Thread.currentThread().getName()); 52 } 53 } 54 55 /** 56 * 2、实现Runnable接口 57 * @author ShammGod 58 * 59 */ 60 class Thread2 implements Runnable{ 61 62 @Override 63 public void run() { 64 // TODO Auto-generated method stub 65 System.out.println("我是实现Runnable接口创建的线程:"+Thread.currentThread().getName()); 66 } 67 } 68 69 /** 70 * 3、实现Callable接口 71 * @author ShammGod 72 * 73 */ 74 class Thread3 implements Callable<String>{ 75 76 @Override 77 public String call() throws Exception { 78 System.out.println("我是实现Callable接口创建的线程:"+Thread.currentThread().getName()); 79 return "返回值"; 80 } 81 82 }