分享一个面试题目的解法:多线程打印数组

遇到个面试题,大概是用N个线程,打印一串数组。
分享一个比较清流的写法。
没用到锁。
用volatile设置的状态,每个线程修改数字,把状态交给下一个线程。
如果有需要,我可以解释和证明一下。
加锁的方式有点复杂,面试的时候写起来可能会有差错,这个可能比较简单。
import java.util.*;

public class Main {
    static volatile int curr = 0;
    static volatile int status = 0;
    static final int THREADS = 4;
    static final int STOP = 100;
    public static void main(String[] args) {
        for (int i = 0; i < THREADS; i++) {
            final int n = i;
            new Thread(() -> {f(n);}, String.valueOf(i)).start();
        }
    }

    public static void f(int number) {
        while (curr <= STOP) {
            if (status == number && curr <= STOP) {
                System.out.println(Thread.currentThread().getName() + "::" + curr);
                curr++;
                status = (status + 1) % THREADS;
            }
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
钱嘛数字而已:辅导员肯定不能同意,不然你出事了,他要承担责任。但是,脚和脑子都长在你自己身上,使用它还需要向辅导员报告么? 辅导员必须按流程拒绝你,然后你拿出成年人的态度,做自己的选择。
点赞 评论 收藏
分享
评论
点赞
16
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务