多线程学习
1.countDownLatch
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
class CountDownLatchTest {
public static void main(String [] args){
CountDownLatch count = new CountDownLatch(1);
for(int i=1; i<4; i++){
new Thread(new CountDownThread(count,i*1000)).start();
}
new Thread(new AwaitThread(count)).start();
new Thread(new AwaitThread(count)).start();
}
//运行线程, 执行countDown()操作
static class CountDownThread implements Runnable{
CountDownLatch count;
private long sleepTime;
public CountDownThread(CountDownLatch count,long sleepTime){
this.count = count;
this.sleepTime = sleepTime;
}
public void run(){
long startTime=System.currentTimeMillis();
System.out.println("CountDownThread : "+this.toString() + " runing ...");
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count.countDown();
System.out.println("CountDownThread : "+this.toString()+" finished ..."+(System.currentTimeMillis()-startTime));
}
}
//等待线程
static class AwaitThread implements Runnable{
CountDownLatch count;
public AwaitThread(CountDownLatch count){
this.count = count;
}
public void run(){
long startTime=System.currentTimeMillis();
System.out.println("AwaitThread : "+this.toString()+" await ...");
try {
this.count.await(10, TimeUnit.SECONDS);//等待两秒钟, 如果CountDownLatch没有countDown到0,自动唤醒,否则立即唤醒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("AwaitThread : "+this.toString()+"finished ... "+(System.currentTimeMillis()-startTime));
}
}
使用场景,n多线程某一步执行需要一个线程作为ready,这时可以使用CoundDownLatch
比如上面,AwaitThread本来要睡眠10S的,但是实际上在有一CountDownThread执行完后就被自动唤醒,基本
性质如下:
- 减数线程不会停留
- 可以唤起多个线程
2.CyclicBarrier
class TestCyclicBarrier {
private static final int THREAD_NUM = 5;
public static class WorkerThread implements Runnable{
CyclicBarrier barrier;
String name;
int count;
public WorkerThread(CyclicBarrier b, String n, int i){
this.barrier = b;
this.name = n;
this.count = i;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
if(this.count<=2){
System.out.println(this.name+" sleep...");
Thread.sleep(10000);
}
System.out.println(this.name + " Worker's waiting");
//线程在这里等待,直到所有线程都到达barrier。
barrier.await();
System.out.println(this.name + " ID:"+Thread.currentThread().getId()+" Working");
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
CyclicBarrier cb = new CyclicBarrier(THREAD_NUM, new Runnable() {
//当所有线程到达barrier时执行
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("\nInside Barrier\n");
}
});
for(int i=0;i<THREAD_NUM;i++){
new Thread(new WorkerThread(cb, "before"+i, i)).start();
}
}
}
特点如下
- 执行线程会暂定等待
- 只能唤起一个ready线程
3.Semaphone
操作系统的信号量是个很重要的概念,在进程控制方面都有应用。Java 并发库 的Semaphore 可以很轻松完成信号量控制,Semaphore可以控制某个资源可被同时访问的个数,acquire()获取一个许可,如果没有就等待,而release()释放一个许可。
如下有5个竞争者,同时并行只有两个名额
class SemaphoreTest implements Runnable{
Semaphore sem;
String name;
public SemaphoreTest(Semaphore s, String name){
this.sem = s;
this.name = name;
}
@Override
public void run() {
try {
System.out.println(this.name + " Thread acquire a source");
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name+ " Thread do something");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name+" Thread release");
sem.release();
}
public static void main(String [] args){
Semaphore sem = new Semaphore(2);
ExecutorService exc = Executors.newCachedThreadPool();
for(int i=0; i<5; i++){
exc.execute(new SemaphoreTest(sem, "name"+i));
}
exc.shutdown();
}
}