线程同步的几种方法,join(),CountDownLatchCyclicBarrier Semaphore

Posted shihx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程同步的几种方法,join(),CountDownLatchCyclicBarrier 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();
}

}

以上是关于线程同步的几种方法,join(),CountDownLatchCyclicBarrier Semaphore的主要内容,如果未能解决你的问题,请参考以下文章

golang协程同步的几种方法

线程同步的几种方法

为什么要线程同步,说出线程同步的几种方法

多线程同步的几种方法

归纳一下:C#线程同步的几种方法

Linux下线程同步的几种方法