当前位置: 代码迷 >> 综合 >> [并发控制] ReentrantLock、Condition打印字母问题
  详细解决方案

[并发控制] ReentrantLock、Condition打印字母问题

热度:57   发布时间:2023-12-12 02:51:53.0

ReentrantLock、Condition打印字母问题

import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import com.google.common.collect.Lists;import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;public class TestLockCondition {
    public static void main(String[] args) {
    Executor executor = Executors.newFixedThreadPool(4);ReentrantLock lock = new ReentrantLock();Condition alphaCondition = lock.newCondition();Condition numericCondition = lock.newCondition();List<String> alphaQueue = Lists.newArrayList();List<String> numericQueue = Lists.newArrayList();IntStream.range(0, 26).forEach(i -> {
    alphaQueue.add((char) ('A' + i) + "");numericQueue.add((i + 1) + "");});executor.execute(() -> {
    IntStream.range(0, 26).forEach(i -> {
    try {
    lock.lock();String alpha = alphaQueue.get(i);Console.print(alpha);numericCondition.signal();alphaCondition.awaitUninterruptibly();} finally {
    lock.unlock();}});});ThreadUtil.safeSleep(1000);executor.execute(() -> {
    IntStream.range(0, 26).forEach(i -> {
    try {
    lock.lock();String num = numericQueue.get(i);Console.print(num);alphaCondition.signal();if (i != 25) {
    numericCondition.awaitUninterruptibly();}} finally {
    lock.unlock();}});});}
}
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import com.google.common.collect.Lists;import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;public class TestLockCondition2 {
    public static void main(String[] args) {
    Executor executor = Executors.newFixedThreadPool(4);Object alphaLock = new Object();Object numericLock = new Object();List<String> alphaQueue = Lists.newArrayList();List<String> numericQueue = Lists.newArrayList();IntStream.range(0, 26).forEach(i -> {
    alphaQueue.add((char) ('A' + i) + "");numericQueue.add((i + 1) + "");});executor.execute(() -> {
    IntStream.range(0, 26).forEach(i -> {
    synchronized (alphaLock) {
    try {
    String alpha = alphaQueue.get(i);Console.print(alpha);if (i != 0) {
    synchronized (numericLock) {
    numericLock.notify();}}alphaLock.wait();} catch (InterruptedException e) {
    e.printStackTrace();}}});});ThreadUtil.safeSleep(100);executor.execute(() -> {
    IntStream.range(0, 26).forEach(i -> {
    synchronized (numericLock) {
    try {
    String num = numericQueue.get(i);Console.print(num);synchronized (alphaLock) {
    alphaLock.notify();}if (i != 25) {
    numericLock.wait();}} catch (InterruptedException e) {
    e.printStackTrace();}}});});}
}
  相关解决方案