码迷,mamicode.com
首页 > 编程语言 > 详细

线程同步的几种方法,join(),CountDownLatch、CyclicBarrier 、Semaphore

时间:2019-12-29 11:07:00      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:local   str   final   lease   release   shu   void   cat   ice   

package com.example.demo.utils;

import java.lang.reflect.Field;
import java.util.concurrent.*;

public class Test1 {

static ThreadLocal threadLocal = new ThreadLocal();
private static CountDownLatch countDownLatch = new CountDownLatch(2);
static int a = 5;
static int b = 1;

public Test1() {
}

public static void main(String args[]) {
Thread t1 = new Thread();  
       Thread t2 = new Thread();

t1.join();
       t2.join();

}

static void f3() {
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) {
executorService.submit(() -> {
int a1 = a--;
try {
Thread.sleep(a * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread" + (a1) + " : " + threadLocal.get());
threadLocal.set(b++);
System.out.println("thread" + (a1) + ": " + threadLocal.get());
});
}
executorService.shutdown();
}

void f2() {
//回环屏障,可以重复使用
CyclicBarrier cyclicBarrier = new CyclicBarrier(7);
//信号量
Semaphore semaphore = new Semaphore(0);
ExecutorService executorService = Executors.newFixedThreadPool(6);
for (int i = 0; i < 6; i++) {
executorService.submit(() -> {
try {
semaphore.release();
Thread.sleep(2000);
System.out.println("step1");

Thread.sleep(2000);
System.out.println("---step2---");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("over");
// semaphore.acquire();
// System.out.println("over9");
executorService.shutdown();
}

void f() {
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(() -> {
try {
Thread.sleep(1000);
System.out.println("child threadone over");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
});

executorService.submit(() -> {
try {
Thread.sleep(1000);
System.out.println("child threadtwo over");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();//递减为0时,阻塞线程恢复
}
});
System.out.println("wait all");
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("all is over");
executorService.shutdown();
}

}

线程同步的几种方法,join(),CountDownLatch、CyclicBarrier 、Semaphore

标签:local   str   final   lease   release   shu   void   cat   ice   

原文地址:https://www.cnblogs.com/shihx/p/12114293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!