jdk 线程池
package com.ylz.threadpool;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.UUID;
import java.util.concurrent.*;
/**
* 描述
* Java提供了Executor框架,该框架围绕Executor接口,
* 其子接口ExecutorService和ThreadPoolExecutor类实现这两个接口。
* 通过使用执行程序,仅需实现Runnable对象并将其发送给执行程序即可执行。
* 它们使您可以利用线程利用的优势,而专注于希望线程执行的任务,而不是线程机制。
* 要使用线程池,我们首先创建一个ExecutorService对象,并将一组任务传递给它。
* ThreadPoolExecutor类允许设置核心和最大池大小。由特定线程运行的可运行对象按顺序执行。
*
*
* 方法 说明
* newFixedThreadPool(int)创建固定大小的线程池。
* newCachedThreadPool()创建一个线程池,该线程池创建新的根据需要创建线程,但之前会重复使用可用的构造线程
* newSingleThreadExecutor()创建一个线程。
*
* 1.创建一个要执行的任务(可运行对象)
* 2.使用执行程序创建执行程序池
* 3.将任务传递给执行程序池
* 4.关闭执行程序池
*
* @Auther: dt
* @Date: 2020/12/26 20:54
*/
public class ThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
singleThreadExecutorPool();
}
private static void createThreadFactoryBuilder() {
//守护线程和主线程保持同步,设置守护线程时主线程完成时子线程也将结束
ThreadFactory factory=new ThreadFactoryBuilder().setNameFormat("demo-2020-zdy").setDaemon(true).build();
ExecutorService executorService=new ThreadPoolExecutor(5,Runtime.getRuntime().availableProcessors(),
0L, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(),factory,new ThreadPoolExecutor.AbortPolicy());
Thread t1=new Thread(()->{
for (int i = 0; i <5 ; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1运行第"+i+"次");
}
});
executorService.submit(t1);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdown();
System.out.println("主线程main运行代码结束");
}
private static void cachedThreadPool() throws InterruptedException {
//缓存线程池 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
ExecutorService executorService= Executors.newCachedThreadPool();
Thread t1=new Thread(()->{
System.out.println("t1正在执行。。。");
System.out.println(Thread.currentThread().getName() + "正在执行。。。");
});
Thread t2=new Thread(()->{
System.out.println("t2正在执行。。。");
System.out.println(Thread.currentThread().getName() + "正在执行。。。");
});
for (int i = 0; i <2 ; i++) {
TimeUnit.SECONDS.sleep(2);
Future future1= executorService.submit(t1);
Future future2= executorService.submit(t2);
System.out.println(Thread.currentThread().getName()+"====");
}
TimeUnit.SECONDS.sleep(2);
Future future3= executorService.submit(t1);
executorService.shutdown();
}
private static void singleThreadExecutorPool() throws InterruptedException, ExecutionException, TimeoutException {
//单线程的线程池
ExecutorService executorService= Executors.newSingleThreadExecutor();
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
return UUID.randomUUID().toString();
}
};
//使用原生的方法
Future future= executorService.submit(callable);
System.out.println("获取的future submit结果是:"+future.get()+"=="+Thread.currentThread().getName());
System.out.println("获取的future submit结果是:"+future.get(2, TimeUnit.SECONDS));
//使用futuretask方法 他是 implements RunnableFuture extends Runnable, Future<V>
FutureTask<String> futureTask=new FutureTask<String>(callable);
executorService.submit(futureTask);
System.out.println("获取的futuretask submit结果是:"+futureTask.get()+"=="+Thread.currentThread().getName());
executorService.shutdown();
}
//固定数量的线程池
private static void fixExcutorPool() {
Thread t1=new Thread(()->{
System.out.println("线程1启动=="+Thread.currentThread().getName());
});
Thread t2=new Thread(()->{
System.out.println("线程2启动=="+Thread.currentThread().getName());
});
ExecutorService executorService= Executors.newFixedThreadPool(2);
Future future=executorService.submit(t1);// ==FutureTask.run();
try {
System.out.println("执行结果:"+future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("线程池状态1:"+executorService.isShutdown());
executorService.execute(t1);
executorService.execute(t2);
executorService.shutdown();
System.out.println("线程池状态2:"+executorService.isShutdown());
}
}
spring线程池
ThreadPoolTaskExecutor poolTaskExecutor=new ThreadPoolTaskExecutor();
poolTaskExecutor.initialize();
poolTaskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
poolTaskExecutor.setKeepAliveSeconds(60);
poolTaskExecutor.setMaxPoolSize(20);
poolTaskExecutor.setAllowCoreThreadTimeOut(true);
poolTaskExecutor.setQueueCapacity(30);
poolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
poolTaskExecutor.setThreadNamePrefix("spring-");
poolTaskExecutor.execute(()->{
for (int i = 0; i <10 ; i++) {
System.out.println(Thread.currentThread().getName()+"线程启动了"+i);
}
});
线程相关锁
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();
new Thread(()->{
lock.lock();
System.out.println("线程1启动one");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
System.out.println("线程1启动two");
}).start();
new Thread(()-> {
lock.lock();
try {
condition.signal();
System.out.println("线程2启动three");
System.out.println("线程2启动four");
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
).start();
Thread t1 = null, t2 = null;
@Test
public void runThread(){
//原子性变动
AtomicInteger i= new AtomicInteger(10);
t1= new Thread(()->{
for (int j = 0; j < 10; j++) {
LockSupport.park();
if(i.getAndDecrement()<0){
System.out.println("1已经买完了还剩:"+0);
LockSupport.unpark(t2);
break;
}else{
i.getAndDecrement();
System.out.println("1卖出一张还剩:"+i);
LockSupport.unpark(t2);
}
}
});
t2= new Thread(()->{
for (int j = 0; j < 10; j++) {
LockSupport.park();
if(i.getAndDecrement()<0){
System.out.println("2已经买完了还剩:"+0);
LockSupport.unpark(t1);
break;
}else{
i.getAndDecrement();
System.out.println("2卖出一张还剩:"+i);
LockSupport.unpark(t1);
}
}
});
t1.start();t2.start();
}
还有synchronized (object)
private static void synchronizedWaitNotify() {
try {
TimeUnit.SECONDS.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
synchronized (object) {
try {
//Thread.sleep(2000);
System.out.println("主线程启动了!!");
object.wait();
System.out.println("主线程被唤醒了!!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t1").start();
new Thread(()->{
synchronized (object){
object.notify();
System.out.println("线程2启动了!!!");
}
},"t2").start();
}