1. Thread
(1) run()方法编写执行代码
(2) start() 启动线程
(3) 通过创建Thread子类的实例创建线程对象
(4) 实例如下:
public class ThreadTest extends Thread{ public void run(){ System.out.println("ThreadTest run name:"+ getName()); } public static void main(String[] args) { for(int i=0;i<10;i++){ new ThreadTest().start(); } } }
2. Runnable
(1) run()方法编写执行代码
(2) start() 启动线程
(3) 先创建 Runnable实现类的实例,并依此作为Thread的target来创建Thread对象,该Thread对象才是真正的线程对象
(4) 实例如下:
public class RunnableTest implements Runnable { @Override public void run() { System.out.println("Runnable Test name "+Thread.currentThread().getName()); } public static void main(String[] args) { for(int i=0; i<10; i++){ RunnableTest rt = new RunnableTest(); new Thread(rt,"线程编号"+i).start(); } } }
3. Callable
(1) call()方法编写执行代码;
(2) 先创建Callable实现类的实例,再使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。
(3) 使用FutureTask对象作为Thread对象的target创建并启动新线程,调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
(4) 实例如下:
public class CallableTest implements Callable<Void> { @Override public Integer call() throws Exception { int i=0; for(;i<10;i++){ System.out.println("Callable Test name "+ Thread.currentThread().getName()+i); } return i; } public static void main(String[] args) { CallableTest ct = new CallableTest(); FutureTask ft = new FutureTask(ct); for(int i=0;i<10;i++){ new Thread(ft,"线程编号 "+i).start(); } try { System.out.println("线程返回值: "+ft.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }