有两个关于线程池的问题:
1,用Executors.newSingleThreadExecutor()创建的线程池的execute()方法 和 用Thread的start()方法有什么不同么?
2, 交通系统的教程里,有这样的代码,
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());//我加上这句查看线程名字
for (int i = 1; i < 1000; i++) {
try {
Thread.sleep((new Random().nextInt(10) + 1) * 1000);
transportation.add(Road.this.name + "--" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
结果是:
pool-1-thread-1
pool-3-thread-1
pool-5-thread-1
pool-7-thread-1
pool-9-thread-1
pool-11-thread-1
pool-13-thread-1
pool-15-thread-1
pool-17-thread-1
pool-19-thread-1
pool-21-thread-1
pool-23-thread-1
换成Thread,
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
for (int i = 1; i < 1000; i++) {
try {
// Thread.sleep((long) (Math.random()*10));
Thread.sleep((new Random().nextInt(10) + 1) * 1000);
transportation.add(Road.this.name + "--" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
结果是:
Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-8
Thread-9
Thread-10
Thread-11
问题:为什么线程池的名字是1,3,5这样的跳呢?而且没看到Thread-0,是为什么 |