蚂蚁金服二面 n个线程打印list.get

/*
评测题目: 完成以下题目,时长30分钟
一、编码题(实现语言不限)
1、编写代码,通过多线程方式,实现列表元素打印
a) 并行线程数N为入参,且 N<List.size()
b) 要求N个线程同时运行
c) 要求线程交替打印,即输出结果为:
线程1 :list.get(0)
线程2:list.get(1)

线程N :list元素(N-1)

线程(size%N):list元素(size-1)
d) 尽量考虑性能最优
*/

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class ThreadTest {
    static int result = 0;

    public static void main(String[] args) throws InterruptedException {
        List<String> a = new ArrayList<>();
        for (int i=0;i<100;i++){
            a.add("面试"+i);
        }
        Duo(5,a);
    }
    public static void Duo(int n, List<String> list) throws InterruptedException {

        if (n>=list.size()){
            return;
        }

        Thread[] threads = new Thread[n];
        final Semaphore[] s = new Semaphore[n];
        for (int i = 0; i < n; i++) {
            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 + ": " + list.get(result++));
                        if (result>=list.size()){
                            System.exit(0);
                        }
                        curSemphore.release();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            threads[i].start();
        }
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值