new Thread 和 线程池的使用
Thread的使用
new Thread(new Runnable(){
@override
public void run(){
}
}).start();
new Thread(Runnable runnable).start();
new Thread(FutureTask<V>{Callable callable}).start();
----项目中不建议使用new Thread的方式创建线程----
new Thread的弊端
1.每次new Thread新建对象性能差。
2.线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
3.缺乏更多功能,如定时执行、定期执行、线程中断。
线程池的使用--(先记录一种)
--
public class Demo1 {
static ThreadPoolExecutor executor = new ThreadPoolExecutor(3,
5,
10,
TimeUnit.SECONDS,
new ArrayBlockingQueue
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int j = i;
String taskName = "任务" + j;
executor.execute(() -> {
//模拟任务内部处理耗时
try {
TimeUnit.SECONDS.sleep(j);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + taskName + "处理完毕");
});
}
//关闭线程池
executor.shutdown();
}
}
用心完成每一件艺术品

浙公网安备 33010602011771号