代码地址:https://github.com/LM917178900/multi-thread.git
1. 实现Runable
@Service
public class RunService implements Runnable {
@Override
public void run() {
System.out.println("=========>runnable");
boolean flag = false;
for(int i = 3 ; i < 100 ; i ++) {
flag = false;
for(int j = 2; j <= Math.sqrt(i) ; j++) {
if(i % j == 0) {
flag = true;
break;
}
}
if(flag == false) {
System.out.print(i+" ");
}
}
}
}
@RestController
public class RunController {
@Resource
private RunService runService;
@GetMapping("test/run")
public String testxx(String id) {
System.out.println("=========>id");
// todo 下面的代码会异步执行
new Thread(runService).start();
System.out.println(id);
return id;
}
2.继承Thread
@Service
public class ThreadService extends Thread{
@Override
public void run() {
boolean flag = false;
for(int i = 3 ; i < 100 ; i ++) {
flag = false;
for(int j = 2; j <= Math.sqrt(i) ; j++) {
if(i % j == 0) {
flag = true;
break;
}
}
if(flag == false) {
System.out.print(i+" ");
}
}
}
}
@RestController
public class ThreadController {
@Resource
private ThreadService threadService;
@GetMapping("test/thread")
public String test_01(String id){
System.out.println("=========>id");
// todo 下面的代码会异步执行;
new Thread(threadService).start();
System.out.println(id);
return id;
}
}
3. 实现Callable
@Service
public class CallService implements Callable<List<Integer>> {
@Override
public List<Integer> call() throws Exception {
boolean flag = false;
List<Integer> lists = new ArrayList<>();
for(int i = 3 ; i < 100 ; i ++) {
flag = false;
for(int j = 2; j <= Math.sqrt(i) ; j++) {
if(i % j == 0) {
flag = true;
break;
}
}
if(flag == false) {
lists.add(i);
}
}
return lists;
}
}
@RestController
public class CallController {
@Resource
private CallService callService;
@GetMapping("test/call")
public String testxx(String id) throws ExecutionException, InterruptedException {
System.out.println("=========>id");
// todo 下面的代码会同步执行;
FutureTask futureTask = new FutureTask(callService);
new Thread(futureTask).start();
Object o = futureTask.get();
System.out.println(o.toString());
System.out.println(id);
return id;
}
}
4. 手写线程池
@Service
public class PoolService implements Callable<List<Integer>> {
@Override
public List<Integer> call() throws Exception {
boolean flag = false;
System.out.println(Thread.currentThread().getName()+" ");
List<Integer> lists = new ArrayList<>();
for(int i = 3 ; i < 100 ; i ++) {
flag = false;
for(int j = 2; j <= Math.sqrt(i) ; j++) {
if(i % j == 0) {
flag = true;
break;
}
}
if(flag == false) {
lists.add(i);
}
}
System.out.println(Thread.currentThread().getName()+" task done");
return lists;
}
}
@RestController
public class PoolController {
@Resource
private PoolService poolService;
@GetMapping("test/pool")
public void testxx(String id) throws ExecutionException, InterruptedException {
// 1.创建固定大小的线程池
// ExecutorService executorService = Executors.newFixedThreadPool(5);
int size = 5;
// 2.修改创建线程池的方式(Executor-->ThreadPoolExecutor)
// ExecutorService executorService = new ThreadPoolExecutor(size,size,0L, TimeUnit.MILLISECONDS,
// new LinkedBlockingQueue<Runnable>());
// 3.添加线程池的名字
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
ExecutorService executorService = new ThreadPoolExecutor(size,size,0L,TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),namedThreadFactory);
List<Future<List<Integer>>> ints = new ArrayList<>();
for(int i = 0 ; i < 5; i ++) {
// todo 会异步执行poolService,(同一个线程内是同步的,线程之间异步交叉执行)
// 提交多个线程任务,并执行
Future<List<Integer>> future = executorService.submit(poolService);
ints.add(future);
}
// 关闭线程池
executorService.shutdown();
// todo 如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。
// 任务已经执行完成,单纯的获取执行结果;
for (Future<List<Integer>> future : ints) {
System.out.println(future.get());
}
}
}
5. spring注解配置线程池
@Configuration
@ComponentScan("com.example.demo.annotate")
@EnableAsync// 在Spring中实现多线程
public class ThreadConfig {
// 这里是声明一个bean,类似于xml中的<bean>标签。
// Executor 就是一个线程池
@Bean
public Executor getExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
}
@Service
public class NoteService {
// 这里可以注入spring中管理的其他bean,这也是使用spring来实现多线程的一大优势
// @Async 定义一个线程任务
@Async // 这里进行标注为异步任务,在执行此方法的时候,会单独开启线程来执行
public void f1(int i) {
System.out.println("f1 : "+ i +":" + Thread.currentThread().getName() + " " + UUID.randomUUID().toString());
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Async
public void f2(int i) {
System.out.println("f2 : " + i +":" + Thread.currentThread().getName() + " " + UUID.randomUUID().toString());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@RestController
public class NoteController {
@Resource
private NoteService noteService;
@GetMapping("test/note")
public String testxx(String id){
for (int i = 0; i < 10; i++) {
noteService.f1(i); // 执行异步任务
noteService.f2(i);
}
return id;
}
}