多线程创建四种方式

//第一种  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 @ 2022-04-17 22:31  黑狗已醒  阅读(124)  评论(0编辑  收藏  举报