JAVA 异步编程-AB线程交替打印(三)

多线程交互

        在Java中,可以使用synchronized关键字或者java.util.concurrent包中的

ReentrantLock来实现多线程交替打印。

方式一:synchronized

public class ThreadJH_Synchronized {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(ThreadJH_Synchronized::threadTwo);
        executorService.submit(ThreadJH_Synchronized::threadOne);
        executorService.shutdown();

    }

    private static Integer count = 0;

    private static Object lockObject = new Object();

    private static void threadOne() {
        while (count < 10) {
            synchronized (lockObject) {
                if (count >= 10) {
                    return;
                }
                Util.mySleep(100);
                Util.printfLog("thread 1,current count=" + count);
                count++;
                //用于唤醒一个在此对象监视器上等待的线程。
                lockObject.notify();
                try {
                    //判断ccount 小于等于满足条件才进入等待。如果不增加判断线程无法结束线程,会死锁
                    if (count < 10) {
                        //让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
                        lockObject.wait();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private static void threadTwo() {
        while (count < 10) {
            synchronized (lockObject) {
                if (count >= 10) {
                    return;
                }
                Util.mySleep(100);
                Util.printfLog("thread 2,current count=" + count);
                count++;
                //用于唤醒一个在此对象监视器上等待的线程。
                lockObject.notify();
                try {
                    if (count < 10) {
                        //让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
                        lockObject.wait();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

方式二:ReentrantLock

public class ThreadJH_ReentrantLock {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(ThreadJH_ReentrantLock::threadOne);
        executorService.submit(ThreadJH_ReentrantLock::threadTwo);
        executorService.shutdown();

    }

    private static Integer count = 0;

    private static ReentrantLock lock = new ReentrantLock();

    //定义了两个`Condition`对象`condition1`和`condition2`,它们用于线程间的协调/通信。
    private static final Condition condition1 = lock.newCondition();
    private static final Condition condition2 = lock.newCondition();

    private static void threadOne() {
        while (count < 10) {
            lock.lock();
            if (count >= 10) {
                return;
            }
            try {
                Util.mySleep(100);
                Util.printfLog("thread 1,current count=" + count);
                count++;
                //唤醒等待:
                // 如果有任何线程正在等待与 `condition2` 关联的 `Lock` 上的 `condition2.await();`,则调用 `signal()` 方法会选择其中一个线程(如果有多个线程在等待)并通知它可以继续执行
                condition2.signal();
                //判断ccount 小于满足条件才进入等待。如果不增加判断线程无法结束线程,会死锁
                if (count < 10) {
                    //当前线程释放锁,等待
                    // 调用`await()`方法的线程会释放与`Condition`关联的`Lock`,允许其他线程获得这个锁并执行它们的任务。
                    condition1.await();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }

        }
    }

    private static void threadTwo() {
        while (count < 10) {
            lock.lock();
            if (count >= 10) {
                return;
            }
            try {
                Util.mySleep(100);
                Util.printfLog("thread 2,current count=" + count);
                count++;
                //唤醒等待:
                condition1.signal();
                if (count < 10) {
                    //当前线程释放锁,等待
                    condition2.await();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }

        }
    }
}

参考:

Java多线程交替打印_java 多线程交替打印-CSDN博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值