* 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();
}
}