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

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();
}

}
posted @ 2019-12-29 10:24  覃上  阅读(174)  评论(0编辑  收藏  举报