多线程创建四种方式

//第一种  Thread
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
log.info("具体业务逻辑");
}
};
thread.setName("t1");
thread.start();


}
//第二种  Runnable
public static void main1(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
log.info("具体业务逻辑");
}
};
Thread t2 = new Thread(runnable, "t2");
t2.start();

}
//第三种  FutureTask  (把一个线程状态传递另外一个线程)
public static void main2(String[] args) throws Exception {
FutureTask<String> task = new FutureTask<>(() -> {
log.info("具体业务逻辑");

return "1";
});
new Thread(task, "t3").start();
String s = task.get();
log.info("主线程获取t3线程的结果:{}", s);

//

}

//第四种   线程池方法
ThreadPoolExecutor threadPoolExecutor = ThreadPoolUtil.creatThreadPoolExecutor(5, 5, 5);

getPayInfoRunnable getPayInfoRunnable = new getPayInfoRunnable(feignToPayService);
threadPoolExecutor.execute(getPayInfoRunnable);
public static ThreadPoolExecutor creatThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliceTime) {

ThreadFactory threadFactory = Executors.defaultThreadFactory();
return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliceTime, TimeUnit.SECONDS
, new LinkedBlockingDeque<>(corePoolSize), threadFactory, (r, executor) -> {
if (!executor.isShutdown()) {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
log.warn("线程中断,阻塞任务提交石失败", e);
}
}
});


}


package com.example.serviceorder.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class getPayInfoRunnable implements Runnable {
private Logger log = LoggerFactory.getLogger(this.getClass());


private FeignToPayService feignToPayService;

/**
* 线程池使用
*
* @param feignToPayService
*/
public getPayInfoRunnable(FeignToPayService feignToPayService) {
this.feignToPayService = feignToPayService;


}

@Override
public void run() {
try {
feignToPayService.getPayInfo();
log.info("多线程结束");
} catch (Exception e) {
log.info("获取信息异常:{}", e);
}

}
}



posted @   黑狗已醒  阅读(125)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 解决跨域问题的这6种方案,真香!
· 分享4款.NET开源、免费、实用的商城系统
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
点击右上角即可分享
微信分享提示