Loading

java创建线程的几种方式

1.继承Thread类

/**
 * @author Ash
 * @date: 2016年8月6日 下午10:56:45 
 * @func: 通过继承Thread类来实现多线程
 * @email 408657544@qq.com
 * @Copyright: 2016 Ash. All rights reserved.
 */
public class ExtendsThread extends Thread{
    public static void main(String[] args) {
        new ExtendsThread().start();
    }
    public void run() {
        System.out.println("hello");
    }
}

2.实现Runnable接口

package com.test.thread;

public class ImplementsRunable {
    public static void main(String[] args) {
        new Thread(new Task()).start();
    }
}
class Task implements Runnable {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("hello");
    }
}

3.使用线程池

public class CallableFutureSample {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < 3; i++) {
            System.out.println(pool.submit(new Task3(i+"")).get());
        }
        pool.shutdown();
    }
}

class Task3 implements Callable<String> {

    private String taskname;
    public Task3(String taskname) {
        this.taskname=taskname;
    }
    @Override
    public String call() throws Exception {
        return taskname+" started";
    }
}

 

posted @ 2016-08-07 00:35  注销111  阅读(196)  评论(0编辑  收藏  举报