Java 创建线程的方法

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值