java.util.concurrent多线程框架 (转)
来源:互联网 发布:安全网络知识竞赛 编辑:程序博客网 时间:2024/05/22 02:05
- package
concurrent; - import
java.util.concurrent.ExecutorService; - import
java.util.concurrent.Executors; - public
class TestThreadPool { - public
static void main(String throwsargs[]) InterruptedException { - //
only two threads - ExecutorService
exec 2);= Executors.newFixedThreadPool( - for(int
index 0;= index 100;< index++) { - Runnable
run new= Runnable() { - public
void run() { - long
time long)= ( (Math.random() 1000);* - System.out.println(“Sleeping
” + time + “ms”); - try
{ - Thread.sleep(time);
- }
catch (InterruptedException e) { - }
- }
- };
- exec.execute(run);
- }
- //
must shutdown - exec.shutdown();
- }
- }
- package
concurrent; - import
static java.util.concurrent.TimeUnit.SECONDS; - import
java.util.Date; - import
java.util.concurrent.Executors; - import
java.util.concurrent.ScheduledExecutorService ; - import
java.util.concurrent.ScheduledFuture; - public
class TestScheduledThread { - public
static void main(String[] args) { - final
ScheduledExecutorService scheduler = Executors - .newScheduledThreadPool(2);
- final
Runnable newbeeper = Runnable() { - int
count 0;= - public
void run() { - System.out.println(new
Date() + ” beep ” + (++count)); - }
- };
- //
1秒钟后运行,并每隔2秒运行一次 - final
ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate( - beeper,
1, 2, SECONDS); - //
2秒钟后运行,并每次在上次任务运行完后等待5秒后重新运行 - final
ScheduledFuture beeperHandle2 = scheduler - .scheduleWithFixedDelay(beeper,
2, 5, SECONDS); - //
30秒后结束关闭任务,并且关闭Scheduler - scheduler.schedule(new
Runnable() { - public
void run() { - beeperHandle.cancel(true);
- beeperHandle2.cancel(true);
- scheduler.shutdown();
- }
- },
30, SECONDS); - }
- }
- package
concurrent; - import
java.text.SimpleDateFormat; - import
java.util.Date; - import
java.util.concurrent.BrokenBarrierException; - import
java.util.concurrent.CyclicBarrier; - import
java.util.concurrent.ExecutorService; - import
java.util.concurrent.Executors; - public
class TestCyclicBarrier { - //
徒步需要的时间: Shenzhen, Guangzhou, Shaoguan, Changsha, Wuhan - private
static int[] timeWalk 5,= { 8, 15, 15, 10 }; - //
自驾游 - private
static int[] timeSelf 1,= { 3, 4, 4, 5 }; - //
旅游大巴 - private
static int[] timeBus 2,= { 4, 6, 6, 7 }; -
- static
String now() { - SimpleDateFormat
sdf new= SimpleDateFormat(“HH:mm:ss”); - return
sdf.format( newDate()) + “: “; - }
-
- static
class Tour implementsRunnable { - private
int[] times; - private
CyclicBarrier barrier; - private
String tourName; - public
Tour(CyclicBarrier int[]barrier, String tourName, times) { - this.times
= times; - this.tourName
= tourName; - this.barrier
= barrier; - }
- public
void run() { - try
{ - Thread.sleep(times[0]
* 1000); - System.out.println(now()
+ tourName + ” Reached Shenzhen”); - barrier.await();
- Thread.sleep(times[1]
* 1000); - System.out.println(now()
+ tourName + ” Reached Guangzhou”); - barrier.await();
- Thread.sleep(times[2]
* 1000); - System.out.println(now()
+ tourName + ” Reached Shaoguan”); - barrier.await();
- Thread.sleep(times[3]
* 1000); - System.out.println(now()
+ tourName + ” Reached Changsha”); - barrier.await();
- Thread.sleep(times[4]
* 1000); - System.out.println(now()
+ tourName + ” Reached Wuhan”); - barrier.await();
- }
catch (InterruptedException e) { - }
catch (BrokenBarrierException e) { - }
- }
- }
-
- public
static void main(String[] args) { - //
三个旅行团 - CyclicBarrier
barrier new= CyclicBarrier( 3); - ExecutorService
exec 3);= Executors.newFixedThreadPool( - exec.submit(new
Tour(barrier, “WalkTour”, timeWalk)); - exec.submit(new
Tour(barrier, “SelfTour”, timeSelf)); - exec.submit(new
Tour(barrier, “BusTour”, timeBus)); - exec.shutdown();
- }
- }
运行结果:
00:02:25: SelfTour Reached Shenzhen
00:02:25: BusTour Reached Shenzhen
00:02:27: WalkTour Reached Shenzhen
00:02:30: SelfTour Reached Guangzhou
00:02:31: BusTour Reached Guangzhou
00:02:35: WalkTour Reached Guangzhou
00:02:39: SelfTour Reached Shaoguan
00:02:41: BusTour Reached Shaoguan
- package
concurrent; - import
java.io.File; - import
java.io.FileFilter; - import
java.util.concurrent.BlockingQueue; - import
java.util.concurrent.ExecutorService; - import
java.util.concurrent.Executors; - import
java.util.concurrent.LinkedBlockingQueue; - import
java.util.concurrent.atomic.AtomicInteger; -
- public
class TestBlockingQueue { - static
long randomTime() { - return
( long)(Math.random() 1000);* - }
-
- public
static void main(String[] args) { - //
能容纳100个文件 - final
BlockingQueue newqueue = LinkedBlockingQueue( 100); - //
线程池 - final
ExecutorService 5);exec = Executors.newFixedThreadPool( - final
File newroot = File(“F:\\JavaLib”); - //
完成标志 - final
File newexitFile = File(“”); - //
读个数 - final
AtomicInteger newrc = AtomicInteger(); - //
写个数 - final
AtomicInteger newwc = AtomicInteger(); - //
读线程 - Runnable
read new= Runnable() { - public
void run() { - scanFile(root);
- scanFile(exitFile);
- }
-
- public
void scanFile(File file) { - if
(file.isDirectory()) { - File[]
files new= file.listFiles( FileFilter() { - public
boolean accept(File pathname) { - return
pathname.isDirectory() - ||
pathname.getPath().endsWith(“.java”); - }
- });
- for
(File one : files) - scanFile(one);
- }
else { - try
{ - int
index = rc.incrementAndGet(); - System.out.println(“Read0:
” + index + ” “ - +
file.getPath()); - queue.put(file);
- }
catch (InterruptedException e) { - }
- }
- }
- };
- exec.submit(read);
- //
四个写线程 - for
( intindex 0;= index 4;< index++) { - //
write thread - final
int NO = index; - Runnable
write new= Runnable() { - String
threadName = “Write” + NO; - public
void run() { - while
( true){ - try
{ - Thread.sleep(randomTime());
- int
index = wc.incrementAndGet(); - File
file = queue.take(); - //
队列已经无对象 - if
(file == exitFile) { - //
再次添加”标志”,以让其他线程正常退出 - queue.put(exitFile);
- break;
- }
- System.out.println(threadName
+ “: ” + index + ” “ - +
file.getPath()); - }
catch (InterruptedException e) { - }
- }
- }
- };
- exec.submit(write);
- }
- exec.shutdown();
- }
- }
- package
concurrent; -
- import
java.util.concurrent.CountDownLatch; - import
java.util.concurrent.ExecutorService; - import
java.util.concurrent.Executors; -
- public
class TestCountDownLatch { - public
static void main(String[] throwsargs) InterruptedException { - //
开始的倒数锁 - final
CountDownLatch newbegin = CountDownLatch( 1); - //
结束的倒数锁 - final
CountDownLatch newend = CountDownLatch( 10); - //
十名选手 - final
ExecutorService 10);exec = Executors.newFixedThreadPool( - for(int
index 0;= index 10;< index++) { - final
int NO 1;= index + - Runnable
run new= Runnable(){ - public
void run() { - try
{ - begin.await();
- Thread.sleep((long)
(Math.random() 10000));* - System.out.println(“No.”
+ NO + ” arrived”); - }
catch (InterruptedException e) { - }
finally { - end.countDown();
- }
- }
- };
- exec.submit(run);
- }
- System.out.println(“Game
Start”); - begin.countDown();
- end.await();
- System.out.println(“Game
Over”); - exec.shutdown();
- }
- }
运行结果:
Game Start
No.4 arrived
No.1 arrived
No.7 arrived
No.9 arrived
No.3 arrived
No.2 arrived
No.8 arrived
No.10 arrived
No.6 arrived
No.5 arrived
Game Over
- package
concurrent; -
- import
java.util.concurrent.Callable; - import
java.util.concurrent.ExecutionException; - import
java.util.concurrent.ExecutorService; - import
java.util.concurrent.Executors; - import
java.util.concurrent.Future; -
- public
class TestFutureTask { - public
static void main(String[] throwsargs) InterruptedException, - ExecutionException
{ - final
ExecutorService 5);exec = Executors.newFixedThreadPool( - Callable
call new= Callable() { - public
String throwscall() Exception { - Thread.sleep(1000
* 5); - return
“Other less important but longtime things.”; - }
- };
- Future
task = exec.submit(call); - //
重要的事情 - Thread.sleep(1000
* 3); - System.out.println(“Let’s
do important things.”); - //
其他不重要的事情 - String
obj = task.get(); - System.out.println(obj);
- //
关闭线程池 - exec.shutdown();
- }
- }
运行结果:
Let’s do important things.
Other less important but longtime things.
- package
concurrent; -
- import
java.util.concurrent.Callable; - import
java.util.concurrent.CompletionService; - import
java.util.concurrent.ExecutionException; - import
java.util.concurrent.ExecutorCompletionServic e; - import
java.util.concurrent.ExecutorService; - import
java.util.concurrent.Executors; - import
java.util.concurrent.Future; -
- public
class TestCompletionService { - public
static void main(String[] throwsargs) InterruptedException, - ExecutionException
{ - ExecutorService
exec 10);= Executors.newFixedThreadPool( - CompletionService
serv = - new
ExecutorCompletionServic e(exec); -
- for
( intindex 0;= index 5;< index++) { - final
int NO = index; - Callable
downImg new= Callable() { - public
String throwscall() Exception { - Thread.sleep((long)
(Math.random() 10000));* - return
“Downloaded Image ” + NO; - }
- };
- serv.submit(downImg);
- }
-
- Thread.sleep(1000
* 2); - System.out.println(“Show
web content”); - for
( intindex 0;= index 5;< index++) { - Future
task = serv.take(); - String
img = task.get(); - System.out.println(img);
- }
- System.out.println(“End”);
- //
关闭线程池 - exec.shutdown();
- }
- }
运行结果:
Show web content
Downloaded Image 1
Downloaded Image 2
Downloaded Image 4
Downloaded Image 0
Downloaded Image 3
End
- package
concurrent; -
- import
java.util.concurrent.ExecutorService; - import
java.util.concurrent.Executors; - import
java.util.concurrent.Semaphore; -
- public
class TestSemaphore { - public
static void main(String[] args) { - //
线程池 - ExecutorService
exec = Executors.newCachedThreadPool(); - //
只能5个线程同时访问 - final
Semaphore newsemp = Semaphore( 5); - //
模拟20个客户端访问 - for
( intindex 0;= index 20;< index++) { - final
int NO = index; - Runnable
run new= Runnable() { - public
void run() { - try
{ - //
获取许可 - semp.acquire();
- System.out.println(“Accessing:
” + NO); - Thread.sleep((long)
(Math.random() 10000));* - //
访问完后,释放 - semp.release();
- }
catch (InterruptedException e) { - }
- }
- };
- exec.execute(run);
- }
- //
退出线程池 - exec.shutdown();
- }
- }
运行结果:
Accessing: 0
Accessing: 1
Accessing: 2
Accessing: 3
Accessing: 4
Accessing: 5
Accessing: 6
Accessing: 7
Accessing: 8
Accessing: 9
Accessing: 10
Accessing: 11
Accessing: 12
Accessing: 13
Accessing: 14
Accessing: 15
Accessing: 16
Accessing: 17
Accessing: 18
Accessing: 19
- java.util.concurrent多线程框架 (转)
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架
- java.util.concurrent 多线程框架---线程池编程(一)
- 线程池--java.util.concurrent 多线程框架(二)
- java.util.concurrent 多线程框架---线程池编程(三)
- java.util.concurrent 多线程框架---线程池编程(五)
- 吾观之一
- 通过fcntl设置FD_CLOEXEC标志有什么用?
- PowerDesigner使用过程当中的问题汇总
- 如果
- Visual Studio 利用附加进程调试DLL, WEB 调试DLL
- java.util.concurrent多线程框架 (转)
- 改变CMFCRibbonBar高度
- 时间比较的几个sql
- 优秀程序员的十个习惯
- iOS: viewWillAppear和viewDidAppear什么时候被调用
- 《算法竞赛入门经典》习题答案 -- Chapter II
- 芯片STC89C52 (宏晶STC)
- Log4j使用总结
- IOS 类似iphone通讯录TableView的完整demo【附源码】