/*
评测题目: 完成以下题目,时长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();
}
}
}