Java 线程池的使用
常用创建线程的方法
集成Thread重写run()
public class TestExtendsThread {
static class Test1ExtendsThread extends Thread {
@Override
public void run() {
System.out.println("我是Test1ExtendsThread的线程!");
}
}
public static void main(String[] args) {
new Test1ExtendsThread().start();
}
}
实现Runnable接口
public class TestImplementsRunnable {
static class ThreadImplementsTunnable implements Runnable{
@Override
public void run() {
System.out.println("Hellow");
}
}
public static void main(String[] args) {
ThreadImplementsTunnable thread=new ThreadImplementsTunnable();
thread.run();
}
}
实现Callable接口
public class TestImplementsCallable {
static class T1 implements Callable{
@Override
public Object call() throws Exception {
System.out.println("Hellow");
return null;
}
}
public static void main(String[] args) {
T1 t1=new T1();
FutureTask futureTask=new FutureTask<>(t1);
futureTask.run();
}
}
- 上面的三种方式:频繁的创建、销毁对象消耗性能;导致占用过多的资源。
线程池的使用
- 线程池和数据库连接池有类似的功效,可以控制线程的数量。可以使线程的使用率提升。减少对象的创建和销毁,可以合理的使用线程资源,保证资源的使用效益最大。
线程池的四种类型以及使用方法
newFixedThreadPool
- 创建一个指定工作线程数量的线程池,如果线程数量达到初始化大小,则将提交的任务保存到池队列中。提高效率节省开销,不会释放空闲资源。
public class FixThreadPool {
public static void method_01() throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
int index = i;
executor.execute(() -> {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + index);
});
}
executor.shutdown();
}
public static void main(String[] args) {
try {
method_01();
}catch (Exception e){
e.printStackTrace();
}
}
}
newCachedThreadPool
- 缓存线程池,可以灵活收回空闲线程,若无可回收则创建新的。默认为1分钟。
public class CachedThreadPoolTest {
public void method() {
try {
this.doOne(5);
this.doTwo(6);
}catch (Exception e){
e.printStackTrace();
}
}
private void doTwo(int x) throws Exception{
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < x; i++) {
final int index = i;
Thread.sleep(4000);
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " " + index);
}
});
}
}
private void doOne(int y) throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < y; i++) {
final int index = i;
Thread.sleep(4000);
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " " + index);
}
});
}
}
public static void main(String[] args) {
CachedThreadPoolTest cachedThreadPoolTest=new CachedThreadPoolTest();
cachedThreadPoolTest.method();
}
}
newScheduledThreadPool
public class ScheduledThreadPoolTest {
public static void method_02() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
long start = new Date().getTime();
System.out.println("scheduleAtFixedRate 开始执行时间:" + DateFormat.getTimeInstance().format(new Date()));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = new Date().getTime();
System.out.println("scheduleAtFixedRate 执行花费时间=" + (end - start) / 1000 + "m");
System.out.println("scheduleAtFixedRate 执行完成时间:" + DateFormat.getTimeInstance().format(new Date()));
System.out.println("======================================");
}
}, 1, 5, TimeUnit.SECONDS);
}
public static void main(String[] args) {
method_02();
}
}
newSingleThreadExecutor
- 只创建唯一的工作线程来执行任务,保证线程按照指定的书序执行,保证顺序的执行任务。
public class SingleThreadExecutorTest {
public static void method_04() {
try {
ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
final int index = i;
executor.execute(() -> {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + index);
});
}
executor.shutdown();
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
method_04();
}
}