要求如下:通过N个线程顺序打印26个英文字母,如给定N=3则输出:
thread0: a
thread1: b
thread2: c
thread0: d
thread1: e
...
理解:个人理解,题目考察的是线程间的交互,如何让线程按顺序领取到各自的任务并按顺序打印结果。
解法一:轮询判断任务是否属于该线程,这种做法的优点是简单,但是不断轮询,在线程数多的情况下反而导致效率低
public class Test {
private volatile static int current = 0; // 当前值
public static void main(String[] args){
int n = 3; // 线程数
int max = 25; // 需打印的最大数
for(int i=0;i<n;i++){
new Thread(new PrintThread(i, n, max),"Thread"+i).start();
}
}
static class PrintThread implements Runnable{
private int n;
private int i;
private int max;
PrintThread(int i,int n, int max){
this.n = n;
this.i = i;
this.max = max;
}
@Override
public void run() {
while(current <= max){
if(current % n == i){ // 判断是否为该线程的任务
synchronized

本文探讨了三种解决方式来让多个线程按顺序打印英文字母:一是线程轮询判断,二是使用condition为每个线程同步,三是为每个线程建立独立的condition并依次唤醒。解法二和三通过条件变量确保线程执行顺序,避免效率问题。
最低0.47元/天 解锁文章
142

被折叠的 条评论
为什么被折叠?



