In-depth understanding of Java multi-threading and concurrency box (first ⑩) - A concurrent auxiliary tools (good play tools)

A, Exchanger exchanger (communication between two threads)

Usage scenarios : and only for the data transmission between the two threads, it is the communication between threads. It is the producer / consumer d of wait () / notify () is the best alternative tools. The core principle: Method exchange () blocking characteristics: This method is called after waiting for the other thread to fetch data, if no other threads get data, has been blocked.

Example: Print alternating parity:

public class Print {
    public static void main(String[] args) {
	// 交换器
	Exchanger<Integer> exchanger = new Exchanger<>();
	// 起始打印数值
	Integer startNumber = 1;
	// 终止的数值
	Integer endNumber= 100;
	// 线程1
	Thread t1 = new Thread(new Thread1(exchanger, startNumber, endNumber));
	Thread t2 = new Thread(new Thread2(exchanger, startNumber, endNumber));
	// 设置线程名称
	t1.setName("thread-no-1");
	t2.setName("thread-no-2");
	// 启动线程
	t1.start();
	t2.start();
}
}
/**
 * 打印奇数的线程
 */
class Thread1 implements Runnable {
private Exchanger<Integer> exchanger;
/** 被打印的数 */
private Integer number;
private final Integer endNumber;
public Thread1(Exchanger<Integer> exchanger, Integer startNumber, Integer endNumber) {
	this.exchanger = exchanger;
	this.number = startNumber;
	this.endNumber = endNumber;
}
@Override
    public void run() {
	while (number <= endNumber) {
		if (number % 2 == 1) {
			System.out.println("线程:" + Thread.currentThread().getName() + " : " + number);
		}
		try {
			exchanger.exchange(number++);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
}
/**
 * 打印偶数的线程
 */
class Thread2 implements Runnable {
private Exchanger<Integer> exchanger;
/** 被打印的数 */
private Integer number;
private final Integer endNumber;
public Thread2(Exchanger<Integer> exchanger, Integer startNumber, Integer endNumber) {
	this.exchanger = exchanger;
	this.number = startNumber;
	this.endNumber = endNumber;
}
@Override
    public void run() {
	while (number <= endNumber) {
		if (number % 2 == 0) {
			System.out.println("线程:" + Thread.currentThread().getName() + " : " + number);
		}
		try {
			exchanger.exchange(number++);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
}
复制代码

Two, Semaphore lights

The core principle: set the maximum number of licenses issued by, to limit the number of concurrent threads. The default is non-fair locks, high efficiency.

public Semaphore(int permits) {
	sync = new NonfairSync(permits);
}
Semaphore semaphore = new Semaphore(5);
try {
	semaphore.acquire();
	// 获取许可
	// 逻辑
}
catch (InterruptedException e) {
	e.printStackTrace();
}
finally {
	semaphore.release();
	// 释放许可
}
复制代码

Three, CountDownLatch countdown latch (lock)

The core principle: Thread way to group tasks. count as a stat state. await () mode will block the current thread until the count is zero.

CountDownLatch countDownLatch = new CountDownLatch(5);
countDownLatch.countDown();
// count - 1
// 预处理
try {
	countDownLatch.await();
	// 阻塞当前线程
	// 大家一起处理的时候,我才处理
}
catch (InterruptedException e) {
	e.printStackTrace();
}
复制代码

Sync synchronizer

private static final class Sync extends AbstractQueuedSynchronizer {
	private static final long serialVersionUID = 4982264981922014374L;
	Sync(int count) {
		setState(count);
	}
	int getCount() {
		return getState();
	}
	protected int tryAcquireShared(int acquires) {
		return (getState() == 0) ? 1 : -1;
	}
	protected Boolean tryReleaseShared(int releases) {
		// 递减 count; 转换为零时发出信号
		for (;;) {
			int c = getState();
			if (c == 0)
			                return false;
			int nextc = c-1;
			if (compareAndSetState(c, nextc))
			                return nextc == 0;
		}
	}
}
复制代码

Four, CyclicBarrier fence cycle (cycle lock)

Core Principle: Based ReentrantLock and Condition. CyclicBarrier not only CountDownLatch functions, as well as to achieve barrier waiting function, that is phased sync.

Compared with CyclicBarrier CountDownLatch

  • CountDownLatch: to perform after a thread (or more), waiting for the other N threads to complete a thing; CyclicBarrier: N threads wait for each other, before the completion of any one thread, all threads must wait.
  • CountDownLatch: disposable; CyclicBarrier: it can be reused.
  • CountDownLatch based AQS; CyclicBarrier based lock and Condition. They are essentially dependent on the volatile and CAS implementation.

Guess you like

Origin juejin.im/post/5e81b96ee51d4546f940a976