Java ReentrantLock 实现两线程三线程交替输出

代码示例展示了如何使用Java的ReentrantLock和Condition或LockSupport来实现两个及三个线程交替输出数字1到最大值的场景。线程通过等待和通知机制确保按顺序打印,并在达到最大值时停止。
摘要由CSDN通过智能技术生成

两线程交替输出123456直到最大值

package org.example;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.Main")
public class Test {
    private static ReentrantLock lock = new ReentrantLock();
    private static boolean isPrint = false;
    private static int count = 0;
    private final static int MAX_COUNT = 30;
    @SneakyThrows
    public static void main(String[] args) {
        Condition condition = lock.newCondition();
        new Thread(() -> {
            while (count < MAX_COUNT) {
                lock.lock();
                while (!isPrint) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                log.debug("{}", count);
                count++;
                isPrint = !isPrint;
                condition.signal();
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            while (count < MAX_COUNT) {
                lock.lock();
                while (isPrint) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                log.debug("{}", count);
                count++;
                isPrint = !isPrint;
                condition.signal();
                lock.unlock();
            }
        }, "t2").start();
    }
}

三线程交替输出123456直到最大值

package org.example;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.Main")
public class Test {
    private static ReentrantLock lock = new ReentrantLock();

    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();
    private static Condition condition3 = lock.newCondition();

    private static int count = 1;
    private final static int MAX_COUNT = 30;

    private static int currPrint = 1;
    private final static int PRINT_SIZE = 3;
    @SneakyThrows
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (count < MAX_COUNT) {
                lock.lock();
                while (currPrint != 1) {
                    try {
                        condition1.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                log.debug("{}", count);
                count ++;
                currPrint ++;
                condition2.signal();
                lock.unlock();
            }
        }, "1");
        Thread t2 = new Thread(() -> {
            while (count < MAX_COUNT) {
                lock.lock();
                while (currPrint != 2) {
                    try {
                        condition2.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                log.debug("{}", count);
                count ++;
                currPrint ++;
                condition3.signal();
                lock.unlock();
            }
        }, "2");
        Thread t3 = new Thread(() -> {
            while (count < MAX_COUNT) {
                lock.lock();
                while (currPrint != 3) {
                    try {
                        condition3.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                log.debug("{}", count);
                count ++;
                currPrint ++;
                currPrint %= PRINT_SIZE;
                condition1.signal();
                lock.unlock();
            }
        }, "3");

        t1.start();
        t2.start();
        t3.start();
    }
}

package org.example;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.Main")
public class Test {
    private static int count = 1;
    private final static int MAX_COUNT = 30;

    private static int currPrint = 1;
    private final static int PRINT_SIZE = 3;

    private static Thread t1;
    private static Thread t2;
    private static Thread t3;

    @SneakyThrows
    public static void main(String[] args) {
        t1 = new Thread(() -> {
            while (count < MAX_COUNT) {
                while (currPrint != 1) {
                    LockSupport.park();
                }
                log.debug("{}", count);
                count++;
                currPrint++;
                LockSupport.unpark(t2);
            }
        }, "1");

        t2 = new Thread(() -> {
            while (count < MAX_COUNT) {
                while (currPrint != 2) {
                    LockSupport.park();
                }
                log.debug("{}", count);
                count++;
                currPrint++;
                LockSupport.unpark(t3);
            }
        }, "2");

        t3 = new Thread(() -> {
            while (count < MAX_COUNT) {
                while (currPrint != 3) {
                    LockSupport.park();
                }
                log.debug("{}", count);
                count++;
                currPrint++;
                currPrint %= PRINT_SIZE;
                LockSupport.unpark(t1);
            }
        }, "3");

        t1.start();
        t2.start();
        t3.start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值