java 多线程--- Thread Runnable Executors
java 实现多线程的整理:
- Thread实现多线程的两种方式:
(1)继承 Thread类,同时重载 run 方法:
- class PrimeThread extends Thread {
- long minPrime;
- primeThread(long minPrime) {
- this.minPrime = minPrime;
- }
- public void run() {
- // compute primes larger than minPrime
- }
- }
- PrimeThread p = new PrimeThread(143);
p.start();
Thread的源码:
- public class Thread implements Runnable {
- /* Make sure registerNatives is the first thing <clinit> does. */
- private static native void registerNatives();
- static {
- registerNatives();
- }
- ......
/* 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 接口的类 参见上面的源码
- package java.lang;
- public interface Runnable {
- 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
--- 因为当程序员不准备修改或者增强这个类的功能的时候,就不应该成为这个类的子类。
- class PrimeRun implements Runnable {
- long minPrime;
- PrimeRun(long minPrime){
- this.minPrime = minPrime;
- }
- public void run() {
- //compute primes larger than minPrime
- ....
- }
- }
- PrimeRun p = new PrimeRun(143);
- new Thread(p).start();
2. Executors
Executor 接口
一个执行提交Runnable 任务的对象。对任务的提交与任务的执行,线程的使用,调度进行解耦。
取代 new Thread(new(RunnableTask())).start()
转而使用:
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
简单的用法:
- class DirectExecutor implements Executor {
- public void execute(Runnable r) {
- r.run();
- }
- }
- class ThreadPerTaskExecutor implements Executor {
- public void execute(Runnable r) {
- new Thread(r).start();
- }
- }
一个复合的Executor:
- class SerialExecutor implements Executor {
- final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
- final Executor executor;
- Runnable active;
- SerialExecutor(Executor executor) {
- this.executor = executor;
- }
- public synchronized void execute(final Runnable r) {
- tasks.offer(new Runnable() {
- public void run() {
- try {
- r.run();
- } finally {
- scheduleNext();
- }
- }
- });
- if (active == null) {
- scheduleNext();
- }
- }
- protected synchronized void scheduleNext() {
- if ((active = tasks.poll()) != null) {
- executor.execute(active);
- }
- }
- }
interface ExecutorService
接口继承Executor提供了方法来管理终止以及可以产生Future结果的同步或者异步任务。
- 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
支持运行异步任务,管理一个线程池,无需手动去创建新的线程。
- public class executors {
- public static void main(String[] args){
- ExecutorService executor = Executors.newSingleThreadExecutor();
- executor.submit(() -> {
- String threadName = Thread.currentThread().getName();
- System.out.println("Hello " + threadName);
- });
- }
- }
但是java进程没有结束,Executors必须显示的停止,可以调用上面ExecutorService中的方法来终止:shutdown() 会等待当前的任务运行完成,shutdownNow() 会终止所有的当前正在运行的任务并且立即关闭executor。
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- public class executors {
- public static void main(String[] args){
- ExecutorService executor = Executors.newSingleThreadExecutor();
- executor.submit(() -> {
- String threadName = Thread.currentThread().getName();
- System.out.println("Hello " + threadName);
- });
- try {
- System.out.println("attempt to shutdown executor");
- executor.shutdown();
- executor.awaitTermination(5, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- System.err.println("tasks interrupted");
- } finally {
- if(!executor.isTerminated()) {
- System.err.println("cancel non-finished tasks");
- }
- executor.shutdownNow();
- System.out.println("shutdown finished");
- }
- }
- }
Executors 还支持另外一种类型的任务:Callable。Callable会返回一个值。
- import java.util.concurrent.*;
- public class callable{
- public static void main(String[] args) throws IllegalStateException,InterruptedException, ExecutionException{
- Callable<Integer> task = () -> {
try {- TimeUnit.SECONDS.sleep(1);
- return 123;
- }
- catch (InterruptedException e) {
- throw new IllegalStateException("task interrupted", e);
- }
- };
- ExecutorService executor = Executors.newFixedThreadPool(1);
- Future<Integer> future = executor.submit(task);
- System.out.println("future done? " + future.isDone());
- Integer res = future.get();
- System.out.println("future done? " + future.isDone());
- System.out.print("result : " + res);
- executor.shutdownNow();
- }
- }
Executors 可以通过invokeAll()一次批量提交多个callable任务。
- import java.util.concurrent.*;
- import java.util.*;
- public class moreCallable{
- public static void main(String[] args) throws InterruptedException{
- ExecutorService executor = Executors.newWorkStealingPool();
- List<Callable<String>> callables = Arrays.asList(
- () -> "task1",
- () -> "task2",
- () -> "task3");
- executor.invokeAll(callables).stream().map(future -> {
- try{
- return future.get();
- }catch (Exception e) {
- throw new IllegalStateException(e);
- }
- }).forEach(System.out::println);
- }
- }
-----
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的更多相关文章
- [java多线程] - Thread&Runnable运用
负载是一个很大的话题,也是一个非常重要的话题.不管是在大的互联网软件中,还是在一般的小型软件,都对负载有一定的要求,负载过高会导致服务器压力过大:负载过低又比较浪费服务器资源,而且当高请求的时候还可能 ...
- 探Java多线程Thread类和Runnable接口之间的联系
首先复习一下Java多线程实现机制,Java实现多线程方法有如下这么几种: 1.继承了(extends)Thread类 2.实现了(implements)Runnable接口 也就是说 有如下两种情 ...
- JAVA多线程Thread VS Runnable详解
要求 必备知识 本文要求基本了解JAVA编程知识. 开发环境 windows 7/EditPlus 演示地址 源文件 进程与线程 进程是程序在处理机中的一次运行.一个进程既包括其所要执行的指令,也 ...
- java多线程(三)-Executors实现的几种线程池以及Callable
从java5开始,类库中引入了很多新的管理调度线程的API,最常用的就是Executor(执行器)框架.Executor帮助程序员管理Thread对象,简化了并发编程,它其实就是在 提供了一个中间层, ...
- java多线程开发,Executors、FutureTask、Callable
java多线程如何应用呢,几乎学java的同学都知道Thread类和Runable接口.继承Thread类或者实现Runable接口,调用thread的start方法即可启动线程. 然后是线程池,就是 ...
- 第39天学习打卡(多线程 Thread Runnable 初始并发问题 Callable )
多线程详解 01线程简介 Process与Thread 程序:是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念. 进程则是执行程序的一次执行过程,它是一个动态的概念.是系统资源分配的 ...
- Java多线程Thread
转自:http://www.cnblogs.com/lwbqqyumidi/p/3804883.html Java总结篇系列:Java多线程(一) 多线程作为Java中很重要的一个知识点,在此还是 ...
- android 多线程Thread,Runnable,Handler,AsyncTask
先看两个链接: 1.http://www.2cto.com/kf/201404/290494.html 2. 链接1: android 的多线程实际上就是java的多线程.android的UI线程又称 ...
- [Java多线程]-Thread和Runable源码解析之基本方法的运用实例
前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...
随机推荐
- Noip2016提高组 组合数问题problem
Day2 T1 题目大意 告诉你组合数公式,其中n!=1*2*3*4*5*...*n:意思是从n个物体取出m个物体的方案数 现给定n.m.k,问在所有i(1<=i<=n),所有j(1< ...
- Python之Scrapy爬虫框架安装及简单使用
题记:早已听闻python爬虫框架的大名.近些天学习了下其中的Scrapy爬虫框架,将自己理解的跟大家分享.有表述不当之处,望大神们斧正. 一.初窥Scrapy Scrapy是一个为了爬取网站数据,提 ...
- Thinkpad 装 centos 7后发热量大处理
原因:由于没有独立显卡驱动导致发热量大,禁用独立显卡去驱动即可. 步骤: 开机按 Fn+F1 进入BIOS. 选择 config 选项卡, 找到 Primary Display [SG] BIOS-- ...
- android中将EditText改成不可编辑的状态
今天在做项目的时候,要想实现一个将EditText变成不可编辑的状态,通过查找博客,发现一个好方法,对于单独的EditText控件我们可以单独设置 1.首先想到在xml中设置Android:edita ...
- 项目jar包管理,使用 .userlibraries 文件增加jar包的可移植性,明确jar包依赖,多项目共用jar包里
当一个普通的项目,在不适用maven 等jar包管理工具的时候,通常我都会直接把jar 包复制lib下,并且在build path 中直接添加额外jar包,或者使用user_libraries包所用的 ...
- 深入研究C语言 第一篇(续)
没有读过第一篇的读者,可以点击这里,阅读深入研究C语言的第一篇. 问题一:如何打印变量的地址? 我们用取地址符&,可以取到变量的偏移地址,用DS可以取到变量的段地址. 1.全局变量: 我们看到 ...
- 【Mail】搭建邮件服务器(LAMP+Postfix+Dovcot+PostfixAdmin+Roundcubemail)
大纲 一.mail部署说明 二.安装准备 三.LMAP环境配置 四.配置postfixadmin 五.配置postfix 六.配置dovecot 七.测试SMTP和POP3服务 八.配置Roundcu ...
- hdoj 2039 三角形
Problem Description 给定三条边,请你判断一下能不能组成一个三角形. Input 输入数据第一行包含一个数M,接下有M行,每行一个实例,包含三个正数A,B,C.其中A,B,C & ...
- mysql +ibatis
1.返回插入ID a.xml <insert id="insert" parameterClass="klcQuestion"> insert in ...
- 页面点击任意js事件,触发360、IE浏览器新页面
在<head></head>标签中 <base target=_self> 不会再增加页面