线程执行器
来源:互联网 发布:联通怎么开通4g加网络 编辑:程序博客网 时间:2024/04/29 21:49
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package
org.concurrency.executorframework;
import
java.util.Date;
import
java.util.concurrent.TimeUnit;
/**
* @author Administrator
* 定义一个任务类,实现Runnable接口
* 只是定义,不执行
*/
public
class
Task
implements
Runnable {
private
Date initDate;
//存储任务创建时间
private
String name;
//存储任务的名称
public
Task() {
}
public
Task(String name) {
initDate =
new
Date();
this
.name = name;
}
@Override
public
void
run() {
// TODO Auto-generated method stub
System.out.printf(
"%s: Task %s Created on: %s\n"
,Thread.currentThread().getName(),name,initDate);
System.out.printf(
"%s: Task %s Started on: %s\n"
,Thread.currentThread().getName(),name,initDate);
try
{
Long duration = (
long
)(Math.random()*
10
);
System.out.printf(
"%s: Task %s: Doing a task during %d seconds\n"
,Thread.currentThread().getName(),name,duration);
TimeUnit.SECONDS.sleep(duration);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.printf(
"%s: Task %s: Finished on: %s\n"
,Thread.currentThread().getName(),name,
new
Date());
}
}
package
org.concurrency.executorframework;
import
java.util.concurrent.Executors;
import
java.util.concurrent.ThreadPoolExecutor;
/**
* @author Administrator
* 它将执行通过执行器接收到的每一个任务。
*/
public
class
Server {
private
ThreadPoolExecutor executor;
public
Server() {
/*线程执行器的创建有两个方式:
* 一个是直接使用ThreadPoolExecutor的构造器来实现
* 一个是通过Executors工厂类来构造执行器和其他相关对象。
* 但是由于TheadPoolExecutor构造器在使用上的复杂性,推荐使用Executors工厂类类创建。
* 这里使用了Executors工厂类的newCacheThreadPoolExecutor()方法来创建一个缓存线程池
* 返回一个ExecutorService对象,因此被强制转换成ThreadPoolExecutor类型。
* 使用线程池的优点是减少新建线程所花费的时间。此类缓存池的缺点是,如果发送过多任务给执行器,系统的复合会过载。
* 当且仅当线程的数量是合理的,或者线程只会运行很短的时间时,适合采用缓存线程池类。
* */
executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
}
/**
* 创建了执行器之后,就可以使用执行器的execute()方法来发送Runnable或者Callable类型的任务。
* 这里的Task是实现了Runnable接口的对象。
* 这里也有一些执行器相关的日志信息:
* getPoolSize():返回执行器线程池中实际的线程数
* getActiveCount():返回执行器中正在执行任务的线程数
* getCompleteTaskCount():返回执行器中已经完成的任务数
* */
public void executeTask(Task task){
System.out.printf("Server: A new task hs arrived\n");
executor.execute(task);
System.out.printf("Server: Pool Size: %d\n",executor.getPoolSize());
System.out.printf("Server: Active Count: %d\n",executor.getActiveCount());
System.out.printf("Server: Completed Tasks: %d\n",executor.getCompletedTaskCount());
}
/**
* 执行器以及ThreadPoolExecutor类一个重要的特性是,通常需要显示地区结束,如果不这样做,那么执行器将继续执行。
* 为了完成执行器的执行,可以使用ThreadPoolExecutor类的shutdown()方法。当执行器执行完所有待运行的任务,它将结束执行。
* 如果再shutdown()方法之后,有新的任务发送给执行器,那么会报出RejectExecutionException异常。
* */
public void endServer(){
executor.shutdown();
}
}
package org.concurrency.executorframework;
/**
* @author Administrator
* main主程序,循环创建Task
*/
public
class
Task_Main {
public
static
void
main(String[] args) {
// TODO Auto-generated method stub
Server server =
new
Server();
for
(
int
i =
0
;i <
100
;i++){
Task task =
new
Task(
"Task"
+i);
server.executeTask(task);
}
server.endServer();
}
}
shutdownNow():这个方法会立即关闭执行器。java培训执行器将不再执行那些正在等待执行的任务。这个方法将返回等待执行的任务列表。调用时,正在执行的任务将继续执行,但这个方法不等待这个任务的完成。
isTerminated():如果调用了shutdown()或shutdownNow()方法,并且执行器完成了关闭过程,那么这个方法将返回true。
isShutdown():如果调用了shutdown()方法,则返回true。
awaitTermination(long timeout,TimeUnit unit):这个方法将阻塞所调用的线程,知道执行器完成任务或者达到所指定的timeout值。
1
2
3
4
5
6
7
8
9
10
11
public
Server() {
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(
5
);
}
public
void
executeTask(Task task){
System.out.printf(
"Server: A new task hs arrived\n"
);
executor.execute(task);
System.out.printf(
"Server: Pool Size: %d\n"
,executor.getPoolSize());
System.out.printf(
"Server: Active Count: %d\n"
,executor.getActiveCount());
System.out.printf(
"Server: Completed Tasks: %d\n"
,executor.getCompletedTaskCount());
System.out.printf(
"Server: Task Count: %d\n"
,executor.getTaskCount());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package
org.concurrency.executorframework.callable;
import
java.util.ArrayList;
import
java.util.List;
import
java.util.Random;
import
java.util.concurrent.Callable;
import
java.util.concurrent.ExecutionException;
import
java.util.concurrent.Executors;
import
java.util.concurrent.Future;
import
java.util.concurrent.ThreadPoolExecutor;
import
java.util.concurrent.TimeUnit;
public
class
FactorialCalculator
implements
Callable<Integer> {
private
Integer number;
//存储任务即将用来计算的数字
public
FactorialCalculator(Integer number) {
this
.number = number;
}
@Override
public
Integer call()
throws
Exception {
// TODO Auto-generated method stub
int
result =
1
;
if
(number ==
0
|| number ==
1
){
result =
1
;
}
else
{
for
(
int
i =
2
;i<number;i++){
result *= i;
TimeUnit.MILLISECONDS.sleep(
20
);
}
}
System.out.printf(
"%s: %d\n"
,Thread.currentThread().getName(),result);
return
result;
}
public
static
void
main(String[] args) {
/*通过Executors工厂类的newFixedThreadPool()方法创建ThreadPoolExecutor执行器来运行任务。这里最多创建2个线程*/
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(
2
);
List<Future<Integer>> resultList =
new
ArrayList<Future<Integer>>();
Random random =
new
Random();
for
(
int
i=
0
;i<
10
;i++){
int
number = random.nextInt(
10
);
FactorialCalculator calculator =
new
FactorialCalculator(number);
Future<Integer> result = executor.submit(calculator);
resultList.add(result);
}
do
{
System.out.printf(
"Main: Number of Completed Tasks:%d\n"
,executor.getCompletedTaskCount());
for
(
int
i=
0
;i<resultList.size();i++){
Future<Integer> result = resultList.get(i);
System.out.printf(
"Main: Task %d: %s\n"
,i,result.isDone());
try
{
TimeUnit.MILLISECONDS.sleep(
50
);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
while
(executor.getCompletedTaskCount() < resultList.size());
System.out.printf(
"Main: Results\n"
);
for
(
int
i =
0
;i<resultList.size();i++){
Future<Integer> result = resultList.get(i);
Integer number =
null
;
try
{
number = result.get();
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch
(ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.printf(
"Main: Task %d\n"
,i,number);
}
executor.shutdown();
}
}
控制任务状态:可以取消任务或者检查任务是否已经完成。为了达到这个目的,可使用isDone()方法来检查任务是否已经完成。
公国call()方法获取返回结果。为了达到这个目的,可以使用get()方法。这个方法一直等待直到Callable对象的call()方法执行完成并返回结果。如果get()方法在等待结果时中断了,则会抛出异常。如果call()方法抛出异常,那个get()也会抛出异常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package
org.concurrency.executorframework.scheduled;
import
java.util.Date;
/**
* @author Administrator
* 创建任务线程
*/
public
class
Task
implements
Runnable {
private
String name;
public
Task(String name) {
this
.name = name;
}
// @Override
// public String call() throws Exception {
// // TODO Auto-generated method stub
// System.out.printf("%s: Starting at : %s\n",name,new Date());
// return "Hello,world";
// }
@Override
public
void
run() {
// TODO Auto-generated method stub
System.out.printf(
"%s: Starting at : %s\n"
,name,
new
Date());
// return "Hello,world";
}
}
package
org.concurrency.executorframework.scheduled;
import
java.util.Date;
import
java.util.concurrent.Executors;
import
java.util.concurrent.ScheduledFuture;
import
java.util.concurrent.ScheduledThreadPoolExecutor;
import
java.util.concurrent.TimeUnit;
/**
* @author Administrator
* 主线程类
*/
public
class
Main {
public
static
void
main(String[] args) {
// TODO Auto-generated method stub
/*使用scheduledThreadPoolExecutor()方法创建ScheduledExecutorService对象,并转化为ScheduledThreadPoolExecutor
* 这个方法接收一个表示线程数量的整数作为参数。
* */
ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
System.out.printf("Main: Starting at: %s\n",new Date());
Task task = new Task("Task");
/*
* 使用scheduledAtFixedRate()方法发送任务。这个方法接收四个参数
* 1.被周期执行的任务
* 2.执行第一次任务执行后的延时时间
* 3.两次执行的时间周期
* 4.第2个和第3个参数的时间单位
* 两次执行之间的周期是指任务咋两次执行开始的时间间隔。
* 这期间可能会存在多个任务实例
* */
ScheduledFuture<?> result = executor.scheduleAtFixedRate(task,
1
,
2
, TimeUnit.SECONDS);
for
(
int
i =
0
;i<
10
;i++){
System.out.printf(
"Main: Delay: %d\n"
,result.getDelay(TimeUnit.MILLISECONDS));
try
{
TimeUnit.MILLISECONDS.sleep(
500
);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
executor.shutdown();
try
{
TimeUnit.SECONDS.sleep(
5
);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.printf(
"Main: Finished at: %s\n"
,
new
Date());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package
org.concurrency.executorframework.callable;
import
java.util.concurrent.Callable;
import
java.util.concurrent.TimeUnit;
/**
* @author Administrator
*
*/
public
class
ReportGenerator
implements
Callable<String> {
/*用来表示数据和报告*/
private String sender;
private String title;
public ReportGenerator(String sender, String title) {
super();
this.sender = sender;
this.title = title;
}
@Override
public String call() throws Exception {
// TODO 让线程休眠一段随机时间
long duration = (long) (Math.random()*10);
System.out.printf("%s_%s: ReportGenerator:Generating a report during %d seconds\n",this.sender,this.title,duration);
TimeUnit.SECONDS.sleep(duration);
String ret = sender+":"+title;
return ret;
}
}
package org.concurrency.executorframework.callable;
import java.util.concurrent.CompletionService;
/**
* @author Administrator
* 用来模拟请求报告
*/
public class ReportRequest implements Runnable {
private String name;
private CompletionService<String> service;
public ReportRequest(String name, CompletionService<String> service) {
this.name = name;
this.service = service;
}
@Override
public void run() {
// TODO 创建了ReportGenerator对象,并使用submit()方法将此对对象发送给CompletionService。
ReportGenerator reportGenerator = new ReportGenerator(name, "Report");
service.submit(reportGenerator);
}
}
package org.concurrency.executorframework.callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @author Administrator
* 这个类将获取ReportGenerator任务的结果
*/
public class ReportProcessor implements Runnable {
private CompletionService<String> service;
private boolean end;
public ReportProcessor(CompletionService<String> service) {
this.service = service;
end = false;
}
@Override
public void run() {
// TODO 获取下一个已经完成任务的Future对象;当然这个任务是采用CompletionService来完成
/*当 *完成服务*任务结束,这些任务中的一个任务就执行结束了,完成服务中存储着Future对象,用来空载它在队列中的队形
* 调用poll()方法访问这个队列,查看是否有任务已经完成,如果有就返回队列中的第一个元素,即一个任务执行完成后的Future对象。
* 当poll()方法返回Future对象后,它将从队列中删除这个Future对象。
* */
while(!end){
try {
Future<String> result = service.poll(20, TimeUnit.SECONDS);
if(result != null){
String report = result.get();
System.out.println("ReportReciver:Report Received:"+ report);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ReportSender: End");
}
}
public void setEnd(boolean end) {
this.end = end;
}
}
package org.concurrency.executorframework.callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author Administrator
* 线程启动类
*/
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService executor = Executors.newCachedThreadPool();
CompletionService<String> service = new ExecutorCompletionService<>(executor);
ReportRequest faceRequest = new ReportRequest("Face", service);
ReportRequest onlineRequest = new ReportRequest("Online", service);
Thread faceThread = new Thread(faceRequest);
Thread onlineThread = new Thread(onlineRequest);
ReportProcessor processor = new ReportProcessor(service);
Thread senderThread = new Thread(processor);
System.out.println("Main: Staring the Threads");
faceThread.start();
onlineThread.start();
senderThread.start();
try {
System.out.println("Main: Waiting for the reportgenerators.");
faceThread.join();
onlineThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Main: Shutting down the executor.");
executor.shutdown();
try {
/*调用awaitTerminated()方法等待所有任务执行结束*/
executor.awaitTermination(
1
, TimeUnit.DAYS);
}
catch
(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
processor.setEnd(
true
);
System.out.println(
"Main:Ends"
);
}
}
0 0
- 线程执行器
- 线程执行器
- java线程执行器
- 线程执行器
- java线程执行器
- 线程并发工具--线程执行器
- 线程事务同步执行器
- 3.1 创建线程执行器
- Executor(线程执行器)
- Executor--线程的执行器
- 第四章线程执行器
- 什么是线程执行器Executor
- Java 线程执行器 详解
- 线程执行
- java中的线程执行器总结!
- 并发编程--创建线程执行器
- 使用 Java 执行器实现线程池
- 使用 Java 执行器实现线程池
- Spark On Yarn:提交Spark应用程序到Yarn
- 欧盟对“中国制造”再下黑手
- Kendo UI常用示例汇总(十三)
- app功能测试知识汇总
- RegisterWindowMessage
- 线程执行器
- iOS 摇一摇的功能
- ionic开发中动态设置ion-scroll的高度
- King's Phone
- C++中的堆与拷贝构造函数
- 没有庸俗的企业,只有不停的战场
- kali linux web渗透测试学习笔记
- C++ 11 for-range 访问容器简单实现
- Eclipse解决“Archive for required library: ...”错误