Java多线程实现和应用总结

上传人:s9****2 文档编号:431614577 上传时间:2023-07-07 格式:DOC 页数:5 大小:42.50KB
返回 下载 相关 举报
Java多线程实现和应用总结_第1页
第1页 / 共5页
Java多线程实现和应用总结_第2页
第2页 / 共5页
Java多线程实现和应用总结_第3页
第3页 / 共5页
Java多线程实现和应用总结_第4页
第4页 / 共5页
Java多线程实现和应用总结_第5页
第5页 / 共5页
亲,该文档总共5页,全部预览完了,如果喜欢就下载吧!
资源描述

《Java多线程实现和应用总结》由会员分享,可在线阅读,更多相关《Java多线程实现和应用总结(5页珍藏版)》请在金锄头文库上搜索。

1、一 Java多线程的实现方式JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。二 继承Thread类实现多线程继承Thread类的方法尽管被我列为一种多线程实现方式,但Thread本质上也是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。看源码如

2、下:Public class Thread implements Runnable 。略。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 stat

3、us value corresponds to state NEW. */ if (threadStatus != 0) throw new IllegalThreadStateException(); group.add(this); start0(); if (stopBeforeStart) stop0(throwableFromStop); private native void start0();。略。这种方式实现多线程很简单,通过自己的类直接extend Thread,并覆盖run()方法,就可以启动新线程并执行自己定义的run()方法。示例如下:public class MyTh

4、read extends Thread Overridepublic void run() System.out.println(currentThread().getName() + =线程开始执行=);try sleep(3000); catch (InterruptedException e) e.printStackTrace();System.out.println(currentThread().getName() + =线程执行结束=);public static void main(String args) MyThread myt1 = new MyThread(); / 创

5、建线程1MyThread myt2 = new MyThread(); / 创建线程2/ 启动线程myt1.start();myt2.start();线程执行结果可能如下:Thread-0=线程开始执行=Thread-1=线程开始执行=Thread-0=线程执行结束=Thread-1=线程执行结束=三 实现Runnable接口实现多线程如果自己的类已经extends另一个类,就无法直接extends Thread,此时,必须实现一个Runnable接口,实例如下:public class MyRunnable implements Runnable public void run() Syst

6、em.out.println(Thread.currentThread().getName() + =线程开始执行=);try Thread.sleep(3000); catch (InterruptedException e) e.printStackTrace();System.out.println(Thread.currentThread().getName() + =线程执行结束=);public static void main(String args) MyRunnable myr = new MyRunnable();/ Runnable无法创建实例,必须借助与ThreadTh

7、read t1 = new Thread(myr); Thread t2 = new Thread(myr);t1.start();t2.start();如果需要启动一个线程,必须首先实例化一个Thread,并传入Runnable实例,调用start()方法启动线程;事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run()。看源码如下:。略。public Thread(Runnable target) init(null, target, Thread- + nextThreadNum(), 0);。略。public v

8、oid run() if (target != null) target.run();。略。四 使用ExecutorService、Callable、Future实现有返回结果的多线程ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。(详细了解Executor框架的可以访问)返回结果的线程是在JDK1.5中引入的新特征,确实很实用,有了这种特征我就不需要再为了得到返回值而大费周折了,而且即便实现了也可能漏洞百出。可返回值的任务必须实现Callable接口,类似的,无返回值的任务使用Runnable接口。执行Callable任务后

9、,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。示例如下:/ 计算start-end内所有数字之和public class MyCallAble implements Callable private Long start;private Long end;public MyCallAble(Long start, Long end) this.start = start;this.end = end;public Long call() throws

10、 Exception Long sum = 0l;for (long i = start; i = end; i+) sum += i;System.out.println(start + - + end + 之和为: + sum);return sum;public class TestMain private static int num = 10;public static void main(String args) ExecutorService execs = Executors.newFixedThreadPool(num);ListFuture futureList = new

11、 ArrayListFuture();for (int i = 0; i num; i+) long begin = i * num + 1;long end = (i + 1) * num;MyCallAble callAble = new MyCallAble(begin, end);Future future = execs.submit(callAble);futureList.add(future);long sum = 0;for (Future fu : futureList) try sum += fu.get().longValue(); catch (Interrupted

12、Exception e) e.printStackTrace(); catch (ExecutionException e) e.printStackTrace();execs.shutdown();/ isTerminated-所有任务执行完后,execs shutdown成功则返回truewhile (execs.isTerminated() System.out.println(= + sum);上述代码中Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。public static ExecutorService newFi

13、xedThreadPool(int nThreads)创建固定数目线程的线程池。public static ExecutorService newCachedThreadPool()创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。public static ExecutorService newSingleThreadExecutor()创建一个单线程化的Executor。public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。五 Thread、Runnable和Callable的区别首先Thread、Runnable、Callable三个接口都是实现多线程的方法;准确说Th

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 办公文档 > PPT模板库 > 总结/计划/报告

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号