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++的位置,比较晦涩。