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();
                    }
                }
            }
        }
    }
}
全部评论

相关推荐

01-23 14:54
同济大学 Java
热爱敲代码的程序媛:给你提几点【专业技能】这个模块里面可优化的地方:1.【具备JVM调优经验】可以去b站上搜一下JVM调优的视频,估计一两个小时凭你的学习能力就能掌握JVM调优的实践方面的技能。2.【MySql优化】MySql这一栏,你去b站或者找个博客看看MySql优化,学一下,如果你本身比较熟悉MySql语句的话,那基本半天时间凭你的学习能力MySql语句优化方面的技能你也能掌握个差不多。以上1,2两点主要是因为我看你专业技能大部分都说的是偏理论,没有写应用。再就是最后,你结合你的项目,想一想你的项目中哪些sql语句是可以用MySql优化的,到时候你面试的时候也好结合着说一下。
点赞 评论 收藏
分享
评论
6
1
分享

创作者周榜

更多
牛客网
牛客企业服务