多线程的实现

Java多线程实现方式主要有三种:
    1、继承Thread类
    2、实现Runnable接口
    3、使用ExecutorService、Callable、Future实现有返回结果的多线程。
其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。

1、继承Thread类实现多线程
    继承Thread类并复写run()方法。
    其本质上也是实现了Runnable接口的一个实例,
    它代表一个线程的实例,启动线程的方法就是通过Thread类的start()实例方法。
    start()方法是一个native方法,它将启动一个新线程,并执行run()方法。
    如果一个类继承了Thread类,那么一个对象就只能调用一次,如果调用多次,则会抛出异常
例如:

    public class MyThread extends Thread { 
      public void run() { 
           System.out.println("MyThread.run()"); 
      } 
    }
    MyThread myThread1 = new MyThread(); 
    myThread1.start();

 重复启动报错:
    Exception in thread "main"  java.lang.IllegalThreadStateException
     at java.lang.Thread.start(  Thread.java:682 )

2、实现Runnable接口方式实现多线程
    实现一个Runnable接口并实现run()方法。
例如:

    public class MyThread extends OtherClass implements Runnable { 
      public void run() { 
           System.out.println("MyThread.run()"); 
      } 
    }

    为了启动MyThread,需要实例化一个Thread,并传入自己的MyThread实例:

    MyThread myThread = new MyThread(); 
    Thread thread = new Thread(myThread); 
    thread.start();

JDK 源码:

    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }
    private native void start0();

native:调用本机的操作系统函数

3、使用ExecutorService、Callable、Future实现有返回结果的多线程-JDK1.5以上
    ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。
    Executor框架 详细可以参见:http://www.iteye.com/topic/366591
    >>> 有返回值的任务必须实现Callable接口,
    >>> 无返回值的任务必须Runnable接口。
    JDK 源码:

        <T> Future<T> submit(Callable<T> task);
        <T> Future<T> submit(Runnable task, T result);
        Future<?> submit(Runnable task);

    执行Callable任务后,可以获取一个Future的对象,
    在该对象上调用get就可以获取到Callable任务返回的Object了,
    再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了
    代码如下:
   

 import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    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;
    /**
     * 有返回值的线程
     */
    @SuppressWarnings("unchecked")
    public class Test {
        @SuppressWarnings("rawtypes")
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            System.out.println("----程序开始运行----");
            Date date1 = new Date();
            int taskSize = 5;
            // 创建一个线程池
            ExecutorService pool = Executors.newFixedThreadPool(taskSize);
            // 创建多个有返回值的任务
            List<Future> list = new ArrayList<Future>();
            for (int i = 0; i < taskSize; i++) {
                Callable c = new MyCallable(i + " ");
                // 执行任务并获取Future对象
                Future f = pool.submit(c);
                // System.out.println(">>>" + f.get().toString());
                list.add(f);
            }
            // 关闭线程池
            pool.shutdown();
            // 获取所有并发任务的运行结果
            for (Future f : list) {
                // 从Future对象上获取任务的返回值,并输出到控制台
                System.out.println(">>>>>>>>>=======" + f.get().toString());
            }
        }
    }
    class MyCallable implements Callable<Object> {
        private String taskNum;

        MyCallable(String taskNum) {
            this.taskNum = taskNum;
        }

        public Object call() throws Exception {
            System.out.println(">>>" + taskNum + "任务启动");
            Date dateTmp1 = new Date();
            Thread.sleep(4000);
            Date dateTmp2 = new Date();
            long time = dateTmp2.getTime() - dateTmp1.getTime();
            System.out.println(">>>" + taskNum + "任务终止");
            return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";
        }
    }

    代码说明:
    上述代码中Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。
        1、 创建固定数目线程的线程池
            => public static ExecutorService newFixedThreadPool(int nThreads)
        2、 创建一个可缓存的线程池
            => public static ExecutorService newCachedThreadPool()
            调用execute 将重用以前构造的线程(如果线程可用)。
            如果现有线程没有可用的,则创建一个新线程并添加到池中。
            终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
        3、创建一个单线程化的Executor
            => public static ExecutorService newSingleThreadExecutor() 
        4、创建一个支持定时及周期性的任务执行的线程池
            => public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
            多数情况下可用来替代Timer类。

    ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。
    如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。

猜你喜欢

转载自my.oschina.net/u/3010171/blog/1785878
今日推荐