要求如下:通过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 (PrintThread.class) {
if(current <= max){
System.out.println(Thread.currentThread().getName() + ": " + (char)(97+current));