用concurrent包下的Executors,ExecutorService,CountDownLatch类写了一小段程序,研究了研究这几个类的功能,代码如下:
package test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 试用concurrent包下的Executors,ExecutorService,CountDownLatch
* 这个例子开启了10个子线程,分别输出了n*10+0到n*10+9的数字,
* 所有的数字都输出完毕后,输出OK
*/
public class Test {
public static void main(String[] args) {
System.out.println("Start");
//倒计数锁存器,初始值10
CountDownLatch latch=new CountDownLatch(10);
//倒计数锁存器,初始值1
CountDownLatch start=new CountDownLatch(1);
//不限定线程数量的线程池,60秒未使用的线程会被回收
ExecutorService service=Executors.newCachedThreadPool();
for(int i=0;i<10;i++){
//submit方法,会执行参数中对象的run方法(类实现了Runnable接口),或者call方法(类实现了Callable接口)
service.submit(new ClassRun(i,latch,start));
}
System.out.println("Execute");
try {
//这3秒之内,所有子线程的run方法都在阻塞状态,堵在了start.await()
Thread.sleep(3000);
//start锁的计数减一,变成0,各线程的run方法不在阻塞,开始往后执行
start.countDown();
//在latch锁的计数被各线程减到0之前,线程阻塞
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("OK");
}
/**
* 可以run的测试类
* 这个类的run方法其实是有问题的
* 如果run方法中的代码报错,那么run方法最后的latch.countDown()代码就不会被执行,
* 那么latch锁的计数就不会被减到0,latch.await()会让主线程一直锁在那里
*/
static class ClassRun implements Runnable{
public int index;
public CountDownLatch latch;
public CountDownLatch start;
public ClassRun(int index,CountDownLatch latch,CountDownLatch start){
this.index=index;
this.latch=latch;
this.start=start;
}
@Override
public void run(){
try {
//如果start锁的计数还没有被减1(变成0),线程阻塞
start.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<10;i++){
System.out.println(index+"--"+(index*10+i));
}
latch.countDown();//执行完毕,给latch锁的计数减一
}
}
}
Start
Execute
0--0
4--40
5--50
5--51
5--52
5--53
7--70
7--71
3--30
4--41
0--1
2--20
1--10
2--21
0--2
4--42
3--31
7--72
8--80
9--90
5--54
6--60
5--55
9--91
8--81
7--73
3--32
4--43
4--44
4--45
0--3
0--4
2--22
1--11
2--23
0--5
4--46
3--33
7--74
8--82
9--92
5--56
6--61
5--57
9--93
8--83
7--75
3--34
4--47
0--6
2--24
1--12
2--25
0--7
4--48
3--35
3--36
7--76
8--84
9--94
5--58
6--62
5--59
9--95
9--96
9--97
9--98
9--99
8--85
7--77
3--37
4--49
0--8
2--26
1--13
2--27
0--9
3--38
7--78
8--86
6--63
8--87
7--79
3--39
2--28
1--14
2--29
8--88
6--64
8--89
1--15
6--65
1--16
6--66
1--17
6--67
1--18
6--68
1--19
6--69
OK
每次跑的结果顺序都不一样,但是都是在所有数字输出结束后再输出的OK