下面是我的测试用例,请指教!
public class Test {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 10; i++) {
exec.execute(new LocalThread());
}
}
}
class LocalThread implements Runnable{
private final Random rand = new Random(47);
@Override
public void run() {
try {
while(!Thread.interrupted()) {
System.out.println(Thread.currentThread().getId() + " - " + rand.nextInt(3));
TimeUnit.MILLISECONDS.sleep(100);
}
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出:
0 - 2
3 - 2
2 - 2
1 - 2
4 - 2
2 - 2
4 - 2
0 - 2
1 - 2
3 - 2
3 - 1
2 - 1
0 - 1
4 - 1
1 - 1
把暂停去掉
class LocalThread implements Runnable{
private final Random rand = new Random(47);
private final int id;
public LocalThread(int id) {
this.id = id;
}
@Override
public void run() {
while(!Thread.interrupted()) {
System.out.println(id + " - " + rand.nextInt(3));
}
}
}
输出
1 - 1
1 - 1
1 - 0
1 - 2
1 - 0
1 - 0
1 - 2
1 - 0
1 - 1
1 - 2
0 - 0
0 - 1
3 - 0
...