实现线程的方式
1 继承thread类 单继承,继承thread类后,无法继承其他类
2 实现runnable接口 可以实现多个接口 无返回值
3 实现Callable接口通过FutureTask包装器来创建Thread线程 有返回值
1 package com.xiangxue.ch1; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.FutureTask; 6 7 public class NewThread { 8 /** 9 * 扩展自Thread类 10 * @param args 11 */ 12 private static class MyThread extends Thread{ 13 public void run(){ 14 System.out.println("I am extends Thread"); 15 } 16 } 17 18 /** 19 * 实现Runnable接口 20 * @param args 21 */ 22 private static class UseRun implements Runnable{ 23 @Override 24 public void run() { 25 System.out.println("I am impelments Runnable;"); 26 } 27 } 28 29 /** 30 * 实现Callable接口,有返回值 31 * @param args 32 */ 33 private static class UseCall implements Callable<String>{ 34 35 @Override 36 public String call() throws Exception { 37 System.out.println("I am impelments Callable;"); 38 return "CallResult"; 39 } 40 } 41 42 43 public static void main(String[] args) throws InterruptedException, ExecutionException { 44 MyThread myThread = new MyThread(); 45 myThread.start(); 46 47 UseRun run = new UseRun(); 48 new Thread(run).start(); 49 50 UseCall useCall = new UseCall(); 51 FutureTask<String> futureTask = new FutureTask<>(useCall); 52 new Thread(futureTask).start(); 53 System.out.println(futureTask.get()); 54 } 55 56 }
打印信息
I am extends Thread I am impelments Runnable; I am impelments Callable; CallResult