java线程(二)

来源:互联网 发布:mac virtualbox 鼠标 编辑:程序博客网 时间:2024/06/06 05:48

1.简介

上面一篇文章介绍了关于线程的基本概念,介绍继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future的具体实现

2.继承Thread类

Thread类是在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的run()方法就可以实现多线程操作了,但是一个类只能继承一个父类,这是此方法的局限.

package com.thread;/** * 描述:继承thread类 * 作者:袁伟倩 * 创建日期:2017-06-02 20:35. */public class ThreadTest extends Thread {    // 构造有参构造函数    public ThreadTest(String name){        super(name);    }    @Override    public void run() {            for (int i = 0; i < 100; i++) {                System.out.println(Thread.currentThread().getName() + " " + i);        }    }    public static void main(String[] args) throws InterruptedException {        ThreadTest threadTesta = new ThreadTest("子线程a");        ThreadTest threadTestb = new ThreadTest("子线程b");        threadTesta.start();        threadTestb.start();    }}

分析
继承Thread类,通过重写run()方法定义了一个新的线程类ThreadTest,其中run()方法的方法体代表了线程需要完成的任务,称之为线程执行体。当创建此线程类对象时一个新的线程得以创建,并进入到线程新建状态。通过调用线程对象引用的start()方法,使得该线程进入到就绪状态,此时此线程并不一定会马上得以执行,这取决于CPU调度时机.

3.实现Runnable接口

实现Runnable接口,并重写该接口的run()方法,该run()方法同样是线程执行体,创建Runnable实现类的实例,并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象

package com.thread;/** * 描述:继承thread类 * 作者:袁伟倩 * 创建日期:2017-06-02 20:35. */class Threads implements Runnable {    @Override    public void run() {        for (int i = 0; i < 100; i++) {            System.out.println(Thread.currentThread().getName() + " " + i);        }    }}public class ThreadTest{        public static void main(String[] args) throws InterruptedException {            Threads threadTesta = new Threads();            Threads threadTestb = new Threads();            // 启动线程//            new Thread(threadTesta).start();//            new Thread(threadTestb).start();            Thread thread1 = new Thread(threadTesta);            Thread thread2 = new Thread(threadTestb);            thread1.start();            thread2.start();    }}

分析:

Runnable定义的子类中没有start()方法,只有Thread类中才有。此时观察Thread类,有一个构造方法:public Thread(Runnable targer)此构造方法接受Runnable的子类实例,也就是说可以通过Thread类来启动Runnable实现的多线程

4.使用Callable和Future接口创建线程

Callable和Future,一个产生结果,一个拿到结果。
具体是创建Callable接口的实现类,并实现clall()方法。并使用FutureTask类来包装Callable实现类的对象,且以此FutureTask对象作为Thread对象的target来创建线程。简单的说Callable接口类被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值。

package com.thread;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;/** * 描述: * 作者:袁伟倩 * 创建日期:2017-06-03 10:10. */public class CallableAndFuture {    public static void main(String[] args) {        Callable<Integer> callable = new Callable<Integer>() {            public Integer call() throws Exception {                return new Random().nextInt(100);            }        };        FutureTask<Integer> future = new FutureTask<Integer>(callable);        new Thread(future).start();        try {            Thread.sleep(5000);// 可能做一些事情            System.out.println(future.get());        } catch (InterruptedException e) {            e.printStackTrace();        } catch (ExecutionException e) {            e.printStackTrace();        }    }}

分析

FutureTask实现了两个接口,Runnable和Future,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,那么就可以使用这个组合,用另一个线程去计算返回值,而当前线程在使用这个返回值之前可以做其它的操作,等到需要这个返回值时,再通过Future得到。

  • 另一种方式使用Callable和Future

通过ExecutorService的submit方法执行Callable,并返回Future,代码如下:

package com.thread;import java.util.Random;import java.util.concurrent.*;/** * 描述: * 作者:袁伟倩 * 创建日期:2017-06-03 10:10. */public class CallableAndFuture {    public static void main(String[] args) {        ExecutorService threadPool = Executors.newSingleThreadExecutor();        Future<Integer> future = threadPool.submit(new Callable<Integer>() {            public Integer call() throws Exception {                return new Random().nextInt(100);            }        });        try {            Thread.sleep(5000);// 可能做一些事情            System.out.println(future.get());        } catch (InterruptedException e) {            e.printStackTrace();        } catch (ExecutionException e) {            e.printStackTrace();        }    }    }

ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程,Executor使我们无需显示的去管理线程的生命周期,是JDK 5之后启动任务的首选方式

  • 执行多个带返回值的任务,并取得多个返回值
package com.thread;import java.util.Random;import java.util.concurrent.*;/** * 描述: * 作者:袁伟倩 * 创建日期:2017-06-03 10:10. */public class CallableAndFuture {    public static void main(String[] args) {        ExecutorService threadPool = Executors.newCachedThreadPool();        CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);        for(int i = 1; i < 5; i++) {            final int taskID = i;            cs.submit(new Callable<Integer>() {                public Integer call() throws Exception {                    return taskID;                }            });        }        // 可能做一些事情        for(int i = 1; i < 5; i++) {            try {                System.out.println(cs.take().get());            } catch (InterruptedException e) {                e.printStackTrace();            } catch (ExecutionException e) {                e.printStackTrace();            }        }    }    }

注:提交到CompletionService中的Future是按照完成的顺序排列的

5.参考

http://blog.csdn.net/ghsau/article/details/7451464

原创粉丝点击