码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程的几种实现方式记录

时间:2016-07-18 16:22:21      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

传统的实现线程的方式为三种,分别为继承Thread类,重写run()方法;实现Runable接口,重写run()方法;实现callable接口,重写call()方法;下面来记录一下最基本的三种编码实现。

一、继承Thread

public class ExtendsThread  extends Thread{

    public void run(){
        System.out.println("Hello Thread");
    }

    public static void main(String[] args) {
        ExtendsThread et1 = new ExtendsThread();
        ExtendsThread et2 = new ExtendsThread();
        et1.start();
        et2.start();
    }

}

  二、实现Runnable接口

public class ImplementsRunable implements Runnable {

    public void run() {
        System.out.println("Hello Thread");
    }

    public static void main(String[] args) {
        ImplementsRunable ir1 = new ImplementsRunable();
        ImplementsRunable ir2 = new ImplementsRunable();
        new Thread(ir1).start();
        new Thread(ir2).start();
    }
}

 三、实现callable接口

public class ImplementsCallable implements Callable {

    private int id;

    public ImplementsCallable(int id){
        this.id = id;
    }

    public String call() throws Exception {
        return "This Thread Id Is : "+this.getId();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();
        List<Future<String>> results = new ArrayList();
        for(int i=1;i<=10;i++){
            results.add(es.submit(new ImplementsCallable(i)));
        }
        Thread.sleep(10000);
        for(Future<String> fs : results){
            if (fs.isDone()) {
                System.out.println(fs.get());
            } else {
                System.out.println("The Thread is not down yet");
            }
        }
        es.shutdown();
    }
}

注:ExecutorService的execute()方法没有返回值,而submit()方法有返回值,类型为Future<T>。

java多线程的几种实现方式记录

标签:

原文地址:http://www.cnblogs.com/watershine/p/5680481.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!