您的位置:首页 > 编程语言 > Java开发

[置顶] java 并发编程实战书籍学习 第五章,CountDownLatch,FutureTask,CyclicBarrier,Semaphore学习

2017-11-14 17:07 761 查看
CountDownLatch

public class CountLanuth implements Runnable {

static CountDownLatch countDownLatch = new CountDownLatch(4);//初始化
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i <4; i++) {
Thread t =new Thread( new CountLanuth());
t.start();
}
countDownLatch.await();//在countDownLatch里的值减到0之前 一直挂起。
System.out.println("wanchen");//这句话会最后输出

}

@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}finally{
countDownLatch.countDown();//务必放到finally语句块中,
}
System.out.println("执行线程"+Thread.currentThread().getName());
}
}

FutureTask

public class Future {
//FutureTask实现RunnableFuture,RunnableFuture实现Future和Runnable
//执行thread.run方法,启动线程的时候会执行到实现了Callable实现类的call方法,同时有返回值
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

FutureTask<String>  futureTask = new FutureTask<String>(new Callable<String>() {

@Override
public String call() throws Exception {
int i =0;
for ( i = 0; i < 3; i++) {
TimeUnit.SECONDS.sleep(1);
}
return i+"";
}
});

Thread thread = new Thread(futureTask);
thread.run();
String string = futureTask.get();//获取线程执行的结果,如果获取不到则一直阻塞,也有超时的方法
System.out.println(string);
}
}

CyclicBarrier

public class CyclicBarry extends Thread{

static CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {
@Override
public void run() {
System.err.println(1010);
}
});//有个runable的构造函数,如果传入这个值则在 barrier.await()之前执行,即再线程一起都执行到await的时候 再先执行runable
public static void main(String[] args) {

for (int i = 0; i < 6; i++) {
new CyclicBarry().start();
}
}

@Override
public void run() {
try {
System.out.println("线程"+Thread.currentThread().getName()+"正在写")
4000
;
            Thread.sleep(100);     
            System.out.println("线程"+Thread.currentThread().getName()+"等待其他线程");
barrier.await();//当执行的线程到达这里的时候,数量为你初始化的数量的时候,则这初始化的线程 看是向下执行自己的任务
} catch (InterruptedException | BrokenBarrierException e) {
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
} 
System.out.println("我们一起执行"+Thread.currentThread().getName());
}
}//如果打印 的结果 和你预想的不一样 ,eclipse,打印顺序问题。


Semaphore

public class Semaphore extends Thread {

static java.util.concurrent.Semaphore semaphore = new java.util.concurrent.Semaphore(3);

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {
Runnable thread = new Runnable() {

@Override
public void run() {
run1();
}
};
Thread thread2 = new Thread(thread);
thread2.start();
}
}

public static void run1() {
try {
System.out.println(Thread.currentThread().getName()+" store");
semaphore.acquire();//只有三个可以获取到,其他的则阻塞
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+ " release");

} catch (InterruptedException e) {

}finally{
semaphore.release();没当释放掉以后,其他线程则可以acquire,有点类似固定长度的线程池


}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: