HJ49 多线程

多线程

http://www.nowcoder.com/questionTerminal/cd99fbc6154d4074b4da0e74224a1582

个人感觉用AtomicInteger写更简单

import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()){
            int total = in.nextInt()*4;
            AtomicInteger count = new AtomicInteger(0);
            int runCount = 4;
            MyPrinter PrinterA = new MyPrinter("A",0,count,total,runCount);
            MyPrinter PrinterB = new MyPrinter("B",1,count,total,runCount);
            MyPrinter PrinterC = new MyPrinter("C",2,count,total,runCount);
            MyPrinter PrinterD = new MyPrinter("D",3,count,total,runCount);
            new Thread(PrinterA).start();
            new Thread(PrinterB).start();
            new Thread(PrinterC).start();
            new Thread(PrinterD).start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("");
        }
    }
}

class MyPrinter implements Runnable{
    String letter;
    int order;
    AtomicInteger count;
    int total;
    int runCount;

    public MyPrinter(String letter, int order, AtomicInteger count, int total,int runCount){
        this.letter = letter;
        this.order = order;
        this.count = count;
        this.total = total;
        this.runCount = runCount;
    }

    @Override
    public void run(){
        while(count.get() != total){
            synchronized(count){
                if(count.get()%runCount == order){
                    System.out.print(letter);
                    count.incrementAndGet();
                    count.notifyAll();
                }
                else{
                    try{
                        count.wait();
                    }
                    catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
全部评论

相关推荐

明天不下雨了:我靠2022了都去字节了还什么读研我教你****:你好,本人985电子科大在读研一,本科西南大学(211)我在字节跳动实习过。对您的岗位很感兴趣,希望获得一次投递机会。
点赞 评论 收藏
分享
菜鸡29号:根据已有信息能初步得出以下几点: 1、硕士排了大本和大专 2、要求会多语言要么是招人很挑剔要么就是干的活杂 3、给出校招薪资范围过于巨大,说明里面的薪资制度(包括涨薪)可能有大坑
点赞 评论 收藏
分享
评论
6
1
分享

创作者周榜

更多
牛客网
牛客企业服务