* Executor:執行某個任務,立馬只有一個execute方法
* ExecutorService:服務跑在後臺,一直運行,等着接收任務:execute/submit 都可以執行任務(execute 執行沒有返回值的,submit執行有返回值的方法) runnable/callable
* Executors: 工廠方法
* Callable : 有返回值,會拋異常
* Runnable : 無返回值,不拋異常
====================
ThreadPool:
package com.chinaoly.sheji.myThread.poolThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
//固定個數的線程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i=0;i<6;i++){
executorService.execute(()->{
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
});
}
System.out.println(executorService);
executorService.shutdown();//線程執行完關閉
// executorService.shutdownNow();//有沒有執行完都關閉
System.out.println(executorService.isTerminated());//所有執行的任務是否都執行完了
System.out.println(executorService.isShutdown());//是否關閉,true是正在關閉中,但未必已經關閉
System.out.println(executorService);
TimeUnit.SECONDS.sleep(5);
System.out.println(executorService.isTerminated());
System.out.println(executorService.isShutdown());
System.out.println(executorService);
}
}
cachedThreadPool:
package com.chinaoly.sheji.myThread.poolThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CachedThreadPool {
/**
* 緩存線程池。默認一開始是0個線程,來一個線程啓動一個線程,若有線程空閒則使用空閒線程。默認線程空閒60秒後關閉
* @param args
*/
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newCachedThreadPool();
System.out.println(service);
for (int i=0;i<2;i++){
service.execute(()->{
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
System.out.println(service);
TimeUnit.SECONDS.sleep(65);
System.out.println(service);
}
}
SingleThreadPool:
package com.chinaoly.sheji.myThread.poolThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 單個線程,能保證任務執行的順序
*/
public class SingleThreadPool {
public static void main(String[] args) {
ExecutorService service=Executors.newSingleThreadExecutor();
service.execute(()->{
for (int i =0;i<5;i++) System.out.println(Thread.currentThread().getName());
});
service.shutdown();
}
}
ScheduledThreadPool:
package com.chinaoly.sheji.myThread.poolThread;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPool {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(4);
service.scheduleAtFixedRate(()->{//以固定的頻率來執行任務,以下每隔500毫秒執行一次任務
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
},0,500,TimeUnit.MILLISECONDS);
// service.shutdown();
}
}
WorkStealingThreadPool:
package com.chinaoly.sheji.myThread.poolThread;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* WorkTealing 是精靈線程(守護線程/後臺線程)
*/
public class WorkStealingPool {
public static void main(String[] args) throws IOException {
ExecutorService service =Executors.newWorkStealingPool();
System.out.println(Runtime.getRuntime().availableProcessors());//打印幾核
service.execute(new R(1000));
service.execute(new R(2000));
service.execute(new R(2000));
service.execute(new R(2000));
service.execute(new R(2000));
System.in.read();
}
static class R implements Runnable{
int r;
public R(int r) {
this.r = r;
}
@Override
public void run() {
try {
Thread.sleep(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(r + " "+Thread.currentThread().getName());
}
}
}
FutureTask:
package com.chinaoly.sheji.myThread.poolThread;
import java.util.concurrent.*;
public class FuturetaskTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> task = new FutureTask<>(()->{
TimeUnit.MILLISECONDS.sleep(500);
return 1000;
});
new Thread(task).start();
System.out.println(task.get());
ExecutorService service = Executors.newFixedThreadPool(5);
Future<Integer> task1 = service.submit(()->{
TimeUnit.MILLISECONDS.sleep(1000);
return 100;
});
System.out.println(task1.isDone());
System.out.println(task1.get());
System.out.println(task1.isDone());
service.shutdown();
}
}
ForkJoinPool:
package com.chinaoly.sheji.myThread.poolThread;
import io.swagger.models.auth.In;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ForkJoinPoolThreadTest {
static int[] nums = new int[1000000];
static final int MAX_NUM = 50000;
static Random r = new Random();
static {
for (int i=0;i<nums.length;i++){
nums[i] = r.nextInt(100);
}
System.out.println(Arrays.stream(nums).sum());//mapreduce
}
/**
* RecursiveAction:沒有返回任務
* RecursiveTask:有返回值
*/
static class AddTask extends RecursiveTask<Long> {
int start,end;
public AddTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if (end -start<MAX_NUM){
long sum = 0L;
for (int i =start;i<end;i++) sum+=nums[i];
System.out.println("from "+start+" to "+end+" : sum = "+sum);
return sum;
}else {
int middle = start+(end-start)/2;
AddTask addTask1 = new AddTask(start,middle);
AddTask addTask2 = new AddTask(middle,end);
addTask1.fork();
addTask2.fork();
return addTask1.join()+addTask2.join();
}
}
}
public static void main(String[] args) throws IOException {
ForkJoinPool forkJoinPool = new ForkJoinPool();
AddTask addTask = new AddTask(0,nums.length);
forkJoinPool.execute(addTask);
System.out.println(addTask.join());
System.in.read();
}
}