n个线程顺序打印0到100数

public class n个线程打印0100 {
    static int result = 0;

    public static void main(String[] args) throws InterruptedException {
        //假设有20个线程
        int n = 20;
        Thread[] threads = new Thread[n];
        //创建n个信号量
        final Semaphore[] s = new Semaphore[n];
        //阻塞1-99号线程,然后让0号线程先执行就行了
        for (int i = 0; i < n; i++) {
            //每个信号量各有1个凭证
            s[i] = new Semaphore(1);
            if (i != n - 1) {
                s[i].acquire();
            }
        }
        for (int i = 0; i < n; i++) {
            final Semaphore lastSemphore = i == 0 ? s[n - 1] : s[i - 1];
            final Semaphore curSemphore = s[i];
            final int index = i;
            threads[i] = new Thread(() -> {
                try {
                    while (true) {
                        lastSemphore.acquire();
                        System.out.println("thread" + index + ": " + result++);
                        if (result > 100) {
                            System.exit(0);
                        }
                        curSemphore.release();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            threads[i].start();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值