一、创建线程的三种方式
方式1:直接new Thread()线程出来
@Test
public void createThread1(){
Thread t1 = new Thread(){
public void run(){
for(int i=0;i<100;i++){
System.out.println("创建线程的方式1"+i);
}
}
};
t1.start();
}
方式2:将Runnable作为参数传到Thread对象中
@Test
public void createThread2(){
Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
System.out.println("创建线程的方式2");
}
});
t2.start();
}
方式3:使用有返回值的线程运行方式
定义类实现callable接口
class CallableImpl implements Callable{
@Override
public String call() throws Exception {
System.out.println("线程执行的方式");
return "这是线程的放回值";
}
}
使用callable接口的实现类作为FutureTask的参数
/**
* @throws ExecutionException
* @throws InterruptedException
* @Description: 创建线程的方式3
* @date 2017年5月18日 上午12:18:32
*/
@Test
public void createThread3() throws InterruptedException, ExecutionException{
FutureTask<String> futureTask = new FutureTask(new CallableImpl());
Thread t3 = new Thread(futureTask);
t3.start();
System.out.println(futureTask.get());
}
第三种方式是有返回值的