線程池
用于建立多個線程
一基本步驟:
- 提供指定線程數量的線程池
- 執行指定的線程的操作。需要提供實作Runnable接口或Callable接口實作類的對象
- 關閉連接配接池
補充:ExecutorService:真正的線程池接口。常見子類ThreadPoolExecutor
二、例題展示
package com.cn.java3;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
class NumberThread implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
class NumberThread1 implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//1. 提供指定線程數量的線程池 ExecutorSevice 是接口
ExecutorService service = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;//這裡進行強制轉換為類,便于進行屬性的設定。
//設定線程池的屬性
// System.out.println(service.getClass());
// service1.setCorePoolSize(15);
// service1.setKeepAliveTime();
//2.執行指定的線程的操作。需要提供實作Runnable接口或Callable接口實作類的對象
service.execute(new NumberThread());//适合适用于Runnable
service.execute(new NumberThread1());//适合适用于Runnable
// service.submit(Callable callable);//适合使用于Callable
//3.關閉連接配接池
service.shutdown();
}
}
就到這裡啦,謝謝大家❥(^_-)