什么时线程池?
线程池是指在初始化一个多线程应用程序中创建的一个线程集合,然后在执行新的任务的时重用这些线程而不是重新创建一个线程,线程池中的线程数量完全取决于可用内存数量和运用程序的需求,然而增加可用线程数是可能的,线程池中每一个线程都有分配一个任务,一旦任务执行完后,会回到池子中并等待下一次的任务分配
1.创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
//最常用的线程池
package com.jlong;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewCachedThreadTest {
public static void main(String[] args) {
//创建可缓存线程
ExecutorService executorService = Executors.newCachedThreadPool();
//执行execute表示创建了线程 类似start()
for (int i = 0; i <30 ; i++) {
int index=i;
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread()+"----"+index);
}
});
}
}
}
2.创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
package com.jlong;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewFiexdThreadPoolTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i <30 ; i++) {
int index=i;
executorService.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread()+"----"+index);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
3.创建一个定长线程池,支持定时及周期性任务执行。延迟执行
package com.jlong;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class NewScheduledThreadTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(6);
scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
System.out.println("三秒钟后执行。。。。。");
}
},3, TimeUnit.SECONDS);
}
}
4.单线程,几乎没有用到
package com.jlong;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewSingleThreadExecutorTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 30; i++) {
int index=i;
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"------"+index);
}
});
}
}
}