




全文预览已结束
下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
一 Java多线程的实现方式JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。二 继承Thread类实现多线程继承Thread类的方法尽管被我列为一种多线程实现方式,但Thread本质上也是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。看源码如下: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 status 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 MyThread 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(); / 创建线程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() System.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无法创建实例,必须借助与ThreadThread 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 void run() if (target != null) target.run();。略。四 使用ExecutorService、Callable、Future实现有返回结果的多线程ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。(详细了解Executor框架的可以访问/topic/366591)返回结果的线程是在JDK1.5中引入的新特征,确实很实用,有了这种特征我就不需要再为了得到返回值而大费周折了,而且即便实现了也可能漏洞百出。可返回值的任务必须实现Callable接口,类似的,无返回值的任务使用Runnable接口。执行Callable任务后,可以获取一个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 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 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 (InterruptedException 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 newFixedThreadPool(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三个接口都是实现多线程的方法;准确说Thead接口是Runnable接口的子类,但是Thread接口提供了启动线程的方法start();而实现了Runnable、Callable接口的实例不能作为线程直接启动;其次实现Callable接口的实例作为线程启动必须借助于其他接口,比如ExecutorService接口的submit()方法,或者是作为FutureTask的构造函数出现,被Thread实例化为线程;而且它更多时候是和Future接口联合使用的;但是实现Runnable接口的实例直接作为Thread的参数就可以被实例化为线程;区别:a. Thread,runnable规定的方法是runnable();而Callable是call();b. Thread,r
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 巡视整改监督培训课件
- 巡察整改课件
- 岩棉板保温课件
- 输煤安全培训项目课件
- 产业协同发展工厂承包合作协议
- 企业长期用车租赁管理服务合同
- 公寓租赁退房协议及押金退还细则
- 创业合伙人知识产权共享与利益分配合作协议
- 小青蛙模仿操课件
- 贴墙砖工人安全培训课件
- 儿童口腔预防保健知识
- 机扩根管治疗讲课件
- 中医护理知识试题及答案
- JG/T 187-2006建筑门窗用密封胶条
- 2025-2030猫砂盆行业市场发展分析及发展前景与投资研究报告
- 电话卡借用免责协议书
- 2025年新教材道德与法治三年级上册第二单元《学科学爱科学》教案设计
- 瑜伽入股协议书范本
- 幼儿园教师语言规范培训
- 服装设计开发委托合同
- 劳动合同附件协议-销售业绩考核协议模板
评论
0/150
提交评论