简单的Thread创建线程
Thread thread = new Thread(()->{
while (true){
try {
System.out.println("当前线程池:"+Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(3L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread.start();
ExecutorService线程池创建线程
ExecutorService是Java提供的线程池,它可以有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞,同时提供定时执行、定期执行、单线程、并发数控制等功能
//这是比较全的线程创建,但比较麻烦,如果对线程管理比较细的可以自己找找
ExecutorService executorService=new ThreadPoolExecutor(5, 6, 7L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
线程池分析
corePoolSize : 5是核心线程数,一旦创建将不会再释放。如果创建的线程数还没有达到指定的核心线程数量,将会继续创建新的核心线程,直到达到最大核心线程数后,
核心线程数将不在增加;如果没有空闲的核心线程,同时又未达到最大线程数,则将继续创建非核心线程;如果核心线程数等于最大线程数,则当核心线程都处于激活状态时,任务将被挂起,等待空闲线程来执行。
maximumPoolSize : 6是最大线程数,允许创建的最大线程数量。如果最大线程数等于核心线程数,则无法创建非核心线程;如果非核心线程处于空闲时,超过设置的空闲时间,则将被回收,释放占用的资源。
keepAliveTime : 7L是当线程空闲时,所允许保存的最大时间,超过这个时间,线程将被释放销毁,但只针对于非核心线程。
unit : TimeUnit.MILLISECONDS是时间单位,TimeUnit.SECONDS等,对应时间的时分秒等。
workQueue : new LinkedBlockingQueue<Runnable>()是任务队列,存储暂时无法执行的任务,等待空闲线程来执行任务。
threadFactory : 线程工程,用于创建线程。
handler : 当线程边界和队列容量已经达到最大时,用于处理阻塞时的程序
简单创建固定线程数线程池
public static void t2(){
int threadNum =10;
// 创建一个固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
// 提交任务给线程池
for (int i = 0; i < threadNum; i++) {
executorService.execute(() -> {
while (true) {
try {
System.out.println("当前线程池:"+Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(3L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
}
// 关闭线程池
if (!executorService.isShutdown())
executorService.shutdown();
}
*在父线程内创建子线程,当父线程结束时,子线程仍然运行
package Test;
import java.util.concurrent.TimeUnit;
public class SubThread {
public static void main(String[] args) {
new Thread(()->{
System.out.println("主线程开始");
// 创建Thread对象
Thread newThread = new Thread(new MyThread(3));
// 启动新线程
newThread.start();
}).start();
System.out.println("主线程结束");
}
// 定义一个Runnable实现类
public static class MyThread extends Thread {
int index;
//这里可以传一些参数
public MyThread(int index) {
this.index=index;
}
@Override
public void run() {
try {
System.out.println("***********************子线程开启****************************");
while (true)
{
System.out.println("***********************子线程运行****************************"+"当前下标:"+index);
TimeUnit.SECONDS.sleep(1L);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}