创建线程的三种方式

一、继承Thread类

java中类是单继承的,继承了该类就无法继承其他类,增加了代码的耦合度,现在提倡的是面向接口编程。

二、实现Runnable接口

相比与方式一,使用实现接口来实现,降低了程序间的耦合度,缺点是没有返回值。

三、实现Callable接口,将Callable实例传给FutureTask(FutureTask实现了RunnableFuture接口,RunnableFuture继承了Runnable接口

和方式二一样也是通过实现接口来创建线程,不同的是可以有返回值。

代码:

package com.shamgod.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * 创建线程的三种方式
 * @author ShammGod
 *
 */
public class TestThread {
    
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //继承Thread类
        Thread t1 = new Thread1();
        t1.start();
        
        //实现Runnable接口,将该实例作为参数创建Thread对象
        Runnable runnable = new Thread2();
        Thread t2 = new Thread(runnable);
        t2.start();
        
        //实现Callable接口,将该实例作为参数创建FutureTask对象,将FutureTask对象作为参数创建Thread对象
        Callable callable = new Thread3();
        FutureTask<String> futureTask = new FutureTask<>(callable);
        Thread t3 = new Thread(futureTask);
        t3.start();
        futureTask.get();//call方法的返回值
        
        //实现Callable接口,将该实例传给线程池的submit方法启动线程
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Callable<String> task = new Thread3();
        Future<String> future = threadPool.submit(task);
        threadPool.shutdown();
        future.get();//call方法的返回值

    }
}
/**
 * 1、继承Thread
 * @author ShammGod
 *
 */
class Thread1 extends Thread{
    @Override
    public void run() {
        System.out.println("我是继承Thread创建的线程:" + Thread.currentThread().getName());
    }
}

/**
 * 2、实现Runnable接口
 * @author ShammGod
 *
 */
class Thread2 implements Runnable{

    @Override
    public void run() {
        // TODO Auto-generated method stub
            System.out.println("我是实现Runnable接口创建的线程:"+Thread.currentThread().getName());
    }
}

/**
 * 3、实现Callable接口
 * @author ShammGod
 *
 */
class Thread3 implements Callable<String>{

    @Override
    public String call() throws Exception {
        System.out.println("我是实现Callable接口创建的线程:"+Thread.currentThread().getName());
        return "返回值";
    }
    
}

 

 

若有不正之处请多多谅解,并欢迎批评指正。

posted @ 2018-07-16 15:24  linchutao_shsf  阅读(276)  评论(0编辑  收藏  举报