java 实现多线程的整理:

  1.   Thread实现多线程的两种方式:

    (1)继承 Thread类,同时重载 run 方法:

  1. class PrimeThread extends Thread {
  2. long minPrime;
  3. primeThread(long minPrime) {
  4. this.minPrime = minPrime;
  5. }
  6.  
  7. public void run() {
  8. // compute primes larger than minPrime
  9.  
  10. }
  11. }
  12.  
  13. PrimeThread p = new PrimeThread(143);
    p.start();

  Thread的源码:

  1. public class Thread implements Runnable {
  2. /* Make sure registerNatives is the first thing <clinit> does. */
  3. private static native void registerNatives();
  4. static {
  5. registerNatives();
  6. }
  7. ......

  /* What will be run. */

   private Runnable target;

   

/**

* If this thread was constructed using a separate

* <code>Runnable</code> run object, then that

* <code>Runnable</code> object's <code>run</code> method is called;

* otherwise, this method does nothing and returns.

* <p>

* Subclasses of <code>Thread</code> should override this method.

*

* @see     #start()

* @see     #stop()

* @see     #Thread(ThreadGroup, Runnable, String)

*/

@Override

public void run() {

if (target != null) {

target.run();

}

}

}

  (2) 声明一个实现了Runnable接口的类。--- Thread 类其实也是实现了Runnable 接口的类 参见上面的源码  

  1. package java.lang;
  2. public interface Runnable {
  3. public abstract void run();

  如果不需要实现Thread 类中的其他方法,可以仅仅实现Runnable接口中的Run()方法来实现多线程。

  "This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class." --- Arthur van Hoff

  --- 因为当程序员不准备修改或者增强这个类的功能的时候,就不应该成为这个类的子类。

  

  1. class PrimeRun implements Runnable {
  2. long minPrime;
  3. PrimeRun(long minPrime){
  4. this.minPrime = minPrime;
  5. }
  6.  
  7. public void run() {
  8. //compute primes larger than minPrime
  9. ....
  10. }
  11. }
  1. PrimeRun p = new PrimeRun(143);
  2. new Thread(p).start();
  1.  

2. Executors

 Executor 接口

  一个执行提交Runnable 任务的对象。对任务的提交与任务的执行,线程的使用,调度进行解耦。

  取代 new Thread(new(RunnableTask())).start()

  转而使用:

  Executor executor = anExecutor;

  executor.execute(new RunnableTask1());

  executor.execute(new RunnableTask2());

简单的用法:

  1. class DirectExecutor implements Executor {
  2. public void execute(Runnable r) {
  3. r.run();
  4. }
  5. }
  6.  
  7. class ThreadPerTaskExecutor implements Executor {
  8. public void execute(Runnable r) {
  9. new Thread(r).start();
  10. }
  11. }

一个复合的Executor:

  1. class SerialExecutor implements Executor {
  2. final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
  3. final Executor executor;
  4. Runnable active;
  5.  
  6. SerialExecutor(Executor executor) {
  7. this.executor = executor;
  8. }
  9.  
  10. public synchronized void execute(final Runnable r) {
  11. tasks.offer(new Runnable() {
  12. public void run() {
  13. try {
  14. r.run();
  15. } finally {
  16. scheduleNext();
  17. }
  18. }
  19. });
  20. if (active == null) {
  21. scheduleNext();
  22. }
  23. }
  24.  
  25. protected synchronized void scheduleNext() {
  26. if ((active = tasks.poll()) != null) {
  27. executor.execute(active);
  28. }
  29. }
  30. }

  interface ExecutorService

  接口继承Executor提供了方法来管理终止以及可以产生Future结果的同步或者异步任务。

  1. public interface ExecutorService extends Executor {
      void shutdown();//停止说有的任务,不会再接收新的任务
      List<Runnable> shutdownNow();//停止全部活跃的任务,停止等待的任务,返回等待执行任务的列表。
      boolean isShutdown(); // 返回true 如果executor 已经被停止
    boolean  isTerminated(); //如果全部的任务在shutDown后都完成了 返回为true.只有在shutdown()或者 shutdownNow() 被调用后才会返回true.
      boolean awaitTermination(long timeout, TimeUnit) throws InterruptedException; //阻塞直到所有的任务在shutdown()请求完成后,或者超时发生,或者现有的线程中断。
      <T>  Future<T>  submit(Callable<T> task); //提交一个值返回的任务运行,同时返回Future类,通过Future 的get()方法可以获得任务的执行结果。
      <T>  Future<T>  submit(Runnable task, T result);
      Future<?>  submit(Runnable task);//提交一个Runnable 任务执行,返回一个Future代表这个任务。
      <T>  List<Future<T>> invokeAll(Colleaciton<? extends Callable<T>> tasks) throws InterruptedException;//执行指定的多个任务,返回Future的list,包含他们的状态,以及运行完成的结果。
      <T>  List<Future<T>> invokeAll(Collectio<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException;//执行给定的任务,返回Future的列表,知道所有的任务都完成或者超时时间达到。
      <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;//执行给定的任务,返回任意一个完成的结果。
      <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;//执行给定的任务,直到任务在超时时间内完成
    }

  class Executors

  支持运行异步任务,管理一个线程池,无需手动去创建新的线程。

  1. public class executors {
  2. public static void main(String[] args){
  3. ExecutorService executor = Executors.newSingleThreadExecutor();
  4. executor.submit(() -> {
  5. String threadName = Thread.currentThread().getName();
  6. System.out.println("Hello " + threadName);
  7. });
  8. }
  9. }

但是java进程没有结束,Executors必须显示的停止,可以调用上面ExecutorService中的方法来终止:shutdown()  会等待当前的任务运行完成,shutdownNow() 会终止所有的当前正在运行的任务并且立即关闭executor。

  1. import java.util.concurrent.ExecutorService;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.TimeUnit;
  4. public class executors {
  5. public static void main(String[] args){
  6. ExecutorService executor = Executors.newSingleThreadExecutor();
  7. executor.submit(() -> {
  8. String threadName = Thread.currentThread().getName();
  9. System.out.println("Hello " + threadName);
  10. });
  11. try {
  12. System.out.println("attempt to shutdown executor");
  13. executor.shutdown();
  14. executor.awaitTermination(5, TimeUnit.SECONDS);
  15. } catch (InterruptedException e) {
  16. System.err.println("tasks interrupted");
  17. } finally {
  18. if(!executor.isTerminated()) {
  19. System.err.println("cancel non-finished tasks");
  20. }
  21. executor.shutdownNow();
  22. System.out.println("shutdown finished");
  23. }
  24. }
  25. }

  Executors 还支持另外一种类型的任务:Callable。Callable会返回一个值。  

  1. import java.util.concurrent.*;
  2.  
  3. public class callable{
  4. public static void main(String[] args) throws IllegalStateException,InterruptedException, ExecutionException{
  5. Callable<Integer> task = () -> {
                  try {
  6. TimeUnit.SECONDS.sleep(1);
  7. return 123;
  8. }
  9. catch (InterruptedException e) {
  10. throw new IllegalStateException("task interrupted", e);
  11. }
  12. };
  13. ExecutorService executor = Executors.newFixedThreadPool(1);
  14. Future<Integer> future = executor.submit(task);
  15. System.out.println("future done? " + future.isDone());
  16.  
  17. Integer res = future.get();
  18. System.out.println("future done? " + future.isDone());
  19. System.out.print("result : " + res);
  20. executor.shutdownNow();
  21. }
  22. }

  Executors 可以通过invokeAll()一次批量提交多个callable任务。

  1. import java.util.concurrent.*;
  2. import java.util.*;
  3.  
  4. public class moreCallable{
  5. public static void main(String[] args) throws InterruptedException{
  6. ExecutorService executor = Executors.newWorkStealingPool();
  7. List<Callable<String>> callables = Arrays.asList(
  8. () -> "task1",
  9. () -> "task2",
  10. () -> "task3");
  11. executor.invokeAll(callables).stream().map(future -> {
  12. try{
  13. return future.get();
  14. }catch (Exception e) {
  15. throw new IllegalStateException(e);
  16. }
  17. }).forEach(System.out::println);
  18. }
  19. }

-----

Executors 是一个包含有很多static静态方法的类,使用时,可以作为一个工具类使用,

  Executors.newWorkStealingPool() 这个方法又拖出来一个类:ForkJoinPool(extends AbstractExecutorService (since 1.7))

后续继续写 Future,ForkJoinPool 以及线程的调度:ScheduledExecutorService。

参考:

http://www.open-open.com/lib/view/open1431307471966.html

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html

http://www.cnblogs.com/lucky_dai/p/5509261.html

java源码

 

java 多线程--- Thread Runnable Executors的更多相关文章

  1. [java多线程] - Thread&Runnable运用

    负载是一个很大的话题,也是一个非常重要的话题.不管是在大的互联网软件中,还是在一般的小型软件,都对负载有一定的要求,负载过高会导致服务器压力过大:负载过低又比较浪费服务器资源,而且当高请求的时候还可能 ...

  2. 探Java多线程Thread类和Runnable接口之间的联系

    首先复习一下Java多线程实现机制,Java实现多线程方法有如下这么几种: 1.继承了(extends)Thread类 2.实现了(implements)Runnable接口 也就是说  有如下两种情 ...

  3. JAVA多线程Thread VS Runnable详解

    要求 必备知识 本文要求基本了解JAVA编程知识. 开发环境 windows 7/EditPlus 演示地址 源文件   进程与线程 进程是程序在处理机中的一次运行.一个进程既包括其所要执行的指令,也 ...

  4. java多线程(三)-Executors实现的几种线程池以及Callable

    从java5开始,类库中引入了很多新的管理调度线程的API,最常用的就是Executor(执行器)框架.Executor帮助程序员管理Thread对象,简化了并发编程,它其实就是在 提供了一个中间层, ...

  5. java多线程开发,Executors、FutureTask、Callable

    java多线程如何应用呢,几乎学java的同学都知道Thread类和Runable接口.继承Thread类或者实现Runable接口,调用thread的start方法即可启动线程. 然后是线程池,就是 ...

  6. 第39天学习打卡(多线程 Thread Runnable 初始并发问题 Callable )

    多线程详解 01线程简介 Process与Thread 程序:是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念. 进程则是执行程序的一次执行过程,它是一个动态的概念.是系统资源分配的 ...

  7. Java多线程Thread

    转自:http://www.cnblogs.com/lwbqqyumidi/p/3804883.html Java总结篇系列:Java多线程(一)   多线程作为Java中很重要的一个知识点,在此还是 ...

  8. android 多线程Thread,Runnable,Handler,AsyncTask

    先看两个链接: 1.http://www.2cto.com/kf/201404/290494.html 2. 链接1: android 的多线程实际上就是java的多线程.android的UI线程又称 ...

  9. [Java多线程]-Thread和Runable源码解析之基本方法的运用实例

    前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...

随机推荐

  1. Noip2016提高组 组合数问题problem

    Day2 T1 题目大意 告诉你组合数公式,其中n!=1*2*3*4*5*...*n:意思是从n个物体取出m个物体的方案数 现给定n.m.k,问在所有i(1<=i<=n),所有j(1< ...

  2. Python之Scrapy爬虫框架安装及简单使用

    题记:早已听闻python爬虫框架的大名.近些天学习了下其中的Scrapy爬虫框架,将自己理解的跟大家分享.有表述不当之处,望大神们斧正. 一.初窥Scrapy Scrapy是一个为了爬取网站数据,提 ...

  3. Thinkpad 装 centos 7后发热量大处理

    原因:由于没有独立显卡驱动导致发热量大,禁用独立显卡去驱动即可. 步骤: 开机按 Fn+F1 进入BIOS. 选择 config 选项卡, 找到 Primary Display [SG] BIOS-- ...

  4. android中将EditText改成不可编辑的状态

    今天在做项目的时候,要想实现一个将EditText变成不可编辑的状态,通过查找博客,发现一个好方法,对于单独的EditText控件我们可以单独设置 1.首先想到在xml中设置Android:edita ...

  5. 项目jar包管理,使用 .userlibraries 文件增加jar包的可移植性,明确jar包依赖,多项目共用jar包里

    当一个普通的项目,在不适用maven 等jar包管理工具的时候,通常我都会直接把jar 包复制lib下,并且在build path 中直接添加额外jar包,或者使用user_libraries包所用的 ...

  6. 深入研究C语言 第一篇(续)

    没有读过第一篇的读者,可以点击这里,阅读深入研究C语言的第一篇. 问题一:如何打印变量的地址? 我们用取地址符&,可以取到变量的偏移地址,用DS可以取到变量的段地址. 1.全局变量: 我们看到 ...

  7. 【Mail】搭建邮件服务器(LAMP+Postfix+Dovcot+PostfixAdmin+Roundcubemail)

    大纲 一.mail部署说明 二.安装准备 三.LMAP环境配置 四.配置postfixadmin 五.配置postfix 六.配置dovecot 七.测试SMTP和POP3服务 八.配置Roundcu ...

  8. hdoj 2039 三角形

    Problem Description 给定三条边,请你判断一下能不能组成一个三角形.   Input 输入数据第一行包含一个数M,接下有M行,每行一个实例,包含三个正数A,B,C.其中A,B,C & ...

  9. mysql +ibatis

    1.返回插入ID a.xml <insert id="insert" parameterClass="klcQuestion"> insert in ...

  10. 页面点击任意js事件,触发360、IE浏览器新页面

    在<head></head>标签中 <base target=_self> 不会再增加页面