Java 中线程池和原生线程貌似有点不一样,求解答。。。
下面附上两个 Demo 完成的功能是主线程等待所有子线程结束然后统计总耗时,第一个使用了线程池,第二个使用 Java 原生线程。
示例一:
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created on 2016/11/25 * * @author annpeter.it@gmail.com
*/public class Bootstrap {
private static ExecutorService executorService = Executors.newFixedThreadPool(10);
private static List list = new LinkedList<>();
private static Random random = new Random();
public static void main(String[] args) throws InterruptedException {
long from = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
final int index = i;
Runnable runnable = () -> {
try {
int time = random.nextInt(5000);
Thread.sleep(time);
System.out.println("i = " + index + " sleep: " + time);
} catch (InterruptedException ignored) {
// passed
}
};
Thread thread = new Thread(runnable);
executorService.execute(thread);
list.add(thread);
}
for (Thread thread : list) {
System.out.println(thread.isAlive());
thread.join();
}
long to = System.currentTimeMillis();
System.out.println("总用时: " + (to - from) );
}
}
示例二:
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created on 2016/11/25 * * @author annpeter.it@gmail.com
*/public class Bootstrap {
private static List list = new LinkedList<>();
private static Random random = new Random();
public static void main(String[] args) throws InterruptedException {
long from = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
final int index = i;
Runnable runnable = () -> {
try {
int time = random.nextInt(5000);
Thread.sleep(time);
System.out.println("i = " + index + " sleep: " + time);
} catch (InterruptedException ignored) {
// passed
}
};
Thread thread = new Thread(runnable);
thread.start();
list.add(thread);
}
for (Thread thread : list) {
System.out.println(thread.isAlive());
thread.join();
}
long to = System.currentTimeMillis();
System.out.println("总用时: " + (to - from) );
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于