【java】让n个线程顺序打印英文字母

要求如下:通过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));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值