• 代码反思(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++的位置,比较晦涩。


  • 相关阅读:
    php 采集程序
    15个实用的PHP正则表达式
    jQuery Mobile优秀网站及资源汇总
    连接ORalce数据库
    Windows Mobile如何观看Webcast
    解决wpf中使用WinformsHost显示滚动条的问题
    利用反射调用类及其属性和方法
    一些实用的vs.net2008 快捷键(已验证)
    WW插件研究
    微软今天公布了下一代Visual Studio和.NET Framework开发工具和平台,该平台将被命名的Visual Studio 2010和.Net Framework 4.0.
  • 原文地址:https://www.cnblogs.com/onliny/p/2207730.html
Copyright © 2020-2023  润新知