交替打印问题

题目描述

启动两个线程,交替打印1-100,不允许使用AtomicInteger等

代码

package com.daleyzou.Test;

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

/**
 * Test1
 * @description
 * 启动两个线程,交替打印1-100,不允许使用AtomicInteger等
 * @author daleyzou
 * @date 2022年04月20日 20:46
 * @version 1.1.1
 */
public class Test1 {
    volatile  int count = 1;
    public  void print() throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();

        Thread thread1 = new Thread(()->{
            lock.lock();
            try {
                while (count < 100){
                    System.out.println(Thread.currentThread().getName() +  count);
                    count++;
                    condition2.signal();
                    condition1.await();
                }
                condition2.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        Thread thread2 = new Thread(()->{
            lock.lock();
            try {
                while (count < 100){
                    condition2.await();
                    System.out.println(Thread.currentThread().getName() + count);
                    count++;
                    condition1.signal();
                }
                condition1.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });

        thread2.start();
        Thread.sleep(100);
        thread1.start();
    }

    public static void main(String[] args) throws InterruptedException {
        Test1 test1 = new Test1();
        test1.print();
        while (true){

        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值