Java 创建线程的方法

来源:互联网 发布:mac上能玩哪些网络游戏 编辑:程序博客网 时间:2024/05/22 13:32
public class ThreadTest<V> {    @org.junit.Test    public void test() throws ExecutionException, InterruptedException {        //继承thread 实现        MyThread myThread = new MyThread();        myThread.start();        //实现Runnable接口实现        MyThread1 myThread1 = new MyThread1();        Thread thread1 = new Thread(myThread1);        thread1.start();        //实现Callable 实现        Callable<V> oneCallable = new MyThread2<>();        FutureTask<V> oneTask = new FutureTask<V>(oneCallable);        //FutureTask 是一个包装类,它通过Callable创建,同时实现了Future 和Runnable 接口        Thread thread2 = new Thread(oneTask);        thread2.start();        /*            使用ExecutorService\Callable\Future 实现有返回结果的线程            这3个接口都属于Executor框架.返回结果的线程是在JDK1.5中引入的            新特性.            可返回值的任务必须实现Callable 接口            执行Callable 任务后,可以获取一个Future 对象,            在该对象上调用get 就可以获取到Callable任务返回的对象            注意:get 方法时阻塞的,即:线程无返回结果,get方法会一直等待            再结合线程池接口ExecutorService 就可以实现有返回结果的多线程        */        int taskSize =5;        //创建一个线程值        ExecutorService pool = Executors.newFixedThreadPool(taskSize);        //创建有多个返回值的任务        List<Future> list = new ArrayList<Future>();        for(int i=0;i<taskSize;i++){            Callable c = new MyThread3<String>(i+" ");            //执行任务并获取Future对象            Future f = pool.submit(c);            list.add(f);        }        //关闭线程池        pool.shutdown();        //获取所有并发任务的运行结果        for(Future f :list){            System.out.println(f.get().toString());        }    }}class MyThread extends Thread {    public void run() {        System.out.println("thread run");    }}class MyThread1 implements Runnable {    @Override    public void run() {        System.out.println("thread run");    }}class MyThread2<V> implements Callable<V> {    @Override    public V call() throws Exception {        System.out.println("thread run");        return null;    }}class MyThread3<String> implements Callable<String> {    //此处String 代表是泛型类型,而不是java.lang.String    private String taskNum;    MyThread3(String taskNum) {        this.taskNum = taskNum;    }    @Override    public String call() throws Exception {        System.out.println(taskNum + "thread run");        long start = System.currentTimeMillis();        Thread.sleep(1000);        long end = System.currentTimeMillis();        System.out.println(taskNum + "thread end");        return (String) (Long.toString( (end-start))+":"+taskNum);    }}
原创粉丝点击