zoukankan      html  css  js  c++  java
  • 代码反思(1)

    1、for循环中需要睡眠等待

    (1) 利用continue

    package org.samuel.ch01;

    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;

    public class Processor {
    List<String> tasks;
    Random random;
    int size;

    public Processor(List<String> tasks) {
    this.tasks = tasks;
    this.random = new Random();
    this.size = tasks.size();
    }

    public void process() {
    for (int i = 0; i < size; ) {
    if (!isRunnable()) {
    try {
    System.out.println("System is busy now...");
    Thread.sleep(1000);
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    }
    continue;
    }
    String task = tasks.get(i);
    doTask(task);
    i++;
    }
    }

      private boolean isRunnable() {
    return random.nextInt() % 2 == 0;
    }

    private void doTask(String task) {
    System.out.println("Finish task : " + task);
    }

    public static void main(String[] args) {
    List<String> tasks = Arrays.asList("samuel", "lin", "by", "badboyby", "linlin");
    Processor processor = new Processor(tasks);
    processor.process();
    }
    }

    (2) 使用while循环

    package org.samuel.ch01;

    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;

    public class AdvancedProcessor {
    List<String> tasks;
    Random random;
    int size;

    public AdvancedProcessor(List<String> tasks) {
    this.tasks = tasks;
    this.random = new Random();
    this.size = tasks.size();
    }

    public void process() {
    for (String task : tasks) {
    while(!isRunnable()) {
    try {
    System.out.println("System is busy now...");
    Thread.sleep(1000);
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    }
    }
    doTask(task);
    }
    }

      private boolean isRunnable() {
    return random.nextInt() % 2 == 0;
    }

    private void doTask(String task) {
    System.out.println("Finish task : " + task);
    }

    public static void main(String[] args) {
    List<String> tasks = Arrays.asList("samuel", "lin", "by", "badboyby", "linlin");
    AdvancedProcessor processor = new AdvancedProcessor(tasks);
    processor.process();
    }
    }

    对比两种方案,从代码逻辑来看,第2种方案更容易理解。第一种方案的continue跳转以及for循环i++的位置,比较晦涩。


  • 相关阅读:
    hiho#1445 重复旋律5 求子串数量 后缀自动机
    SPOJ LCS2 后缀自动机
    SPOJ-LCS 后缀自动机
    bzoj 3261 最大异或和 可持久化字典树(01树)
    【洛谷1297】单选错位
    【HAOI2008】木棍分割
    【SDOI2016】排列计数
    【HAOI2008】下落的圆盘
    【HAOI2008】硬币购物
    【洛谷5520】青原樱
  • 原文地址:https://www.cnblogs.com/onliny/p/2207730.html
Copyright © 2011-2022 走看看