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源码解析 前面 ...
随机推荐
- Android学习---通过内容提供者(ContentProvider)操作另外一个应用私有数据库的内容
一.什么是ContentProvider? ContentProvider直译过来就是内容提供者,主要作用就是A应用提供接口给B应用调用数据,和之前介绍的sharedPreference和直接开放文件 ...
- [刘阳Java]_MyBatis_动态SQL标签用法_第7讲
1.MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. 2.MyBatis中用于实现动态SQL的元素主要有 if choose(when,otherwi ...
- Android开发学习笔记:浅谈显示Intent和隐式Intent
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://liangruijun.blog.51cto.com/3061169/655132 ...
- TCP协议学习记录 (三) Ping程序 RR选项 记录路由hop
一开始想直接在上个程序改,自己构造IP包头,但后来发现不行,微软不让干了,所以后来选用libcap库来收发包 代码写的很乱.. #pragma pack(4) #define ECHO_REQUEST ...
- jQuery系列之操作select标签
每次看完东西基本就忘了,现在决定写一下博客来记录,不知道效果咋样. 一.jQuery操作选择器 1.基本选择器 关于基本选择器,我就不用太多说了,包括了ID.类.标签等选择器. 2.层次选择器 我觉得 ...
- 为何jquery动态添加的input value无法提交到数据库?【坑】
有两个输入框,我想让第一个输入框失去焦点以后,第二个输入框自动获取第一个输入框的value为默认值,jquery代码如下,可以正常显示,但是用PHP提交数据,并插入数据库的时候确实空值,尚未查找到原因 ...
- 第五回. $e$ 的引入
假如你有 $1$ 块钱, 存银行, 利率为 $100\%$, 那么一年后本息和为$$1+1=2.$$ 如果你换种存法, 存半年, 把本息和取出来, 再存半年, 那么一年后本息和为$$\left(1+\ ...
- new 一个button 然后dispose,最后这个button是null吗???
结果当然不是,button虽然释放了资源,但是它扔指向原来的那个地址,故不等于null 可以用button.isdispose==true判断
- advanced validation on purchase.
安装模块 此模块在 标准功能的 2级审批基础上 增加 老板审批 增加 不同技术类和 非技术类的分支 核心审批工作流 如下图示 为审批用户 授予 purchase manager 权限 否则,看不到 审 ...
- --with-http_realip_module选项(后台Nginx服务器记录原始客户端的IP地址 )
转自:http://blog.itpub.net/27043155/viewspace-734234/ 通过这个模块允许我们改变客户端请求头中客户端IP地址值(例如,X-Real-IP 或 X-For ...