创建线程的3种方式
Thread:继承Thread类,可以直接使用this关键字,不能继承其他类;
runnable:可以继承其他类,多个线程共享一个target,必须使用Thread.currentThread().getName()获取当前线程名称,推荐使用这种;
callable:跟runnable差不多,不过他可以有返回值跟抛出异常;
继承Thread类
package com.jspjs.test.thread;import java.util.concurrent.Callable;import java.util.concurrent.FutureTask;public class CreateByCallable implements Callable<Integer> {@Overridepublic Integer call() throws Exception {Integer i=0;for(;i<10;i++){System.out.println(Thread.currentThread().getName()+"|"+i);}return i;}/** * @param args */public static void main(String[] args) {CreateByCallable callable=new CreateByCallable();FutureTask<Integer> task=new FutureTask<Integer>(callable);new Thread(task,"线程1").start();try {System.out.println("子线程的返回值:"+task.get());} catch (Exception e) {e.printStackTrace();}}}