1.创建多线程的7种方式
(1)继承Thrend
(2)实现Runnable、内部类、lambda(如下)
public class RunnableLambda {
public static void main(String[] args) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "运行了");
}).start();
System.out.println(Thread.currentThread().getName() + "运行了");
}
}
其实就是实现了Runnable
(3)callable和future
有返回值,如下
package com.example.test.demo.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableDemo implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "运行了");
return "我是返回值";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallableDemo CallableDemo = new CallableDemo();
FutureTask<String> task = new FutureTask<String>(CallableDemo);
new Thread(task).start();
String s = task.get();
System.out.println(s);
System.out.println(Thread.currentThread().getName() + "运行了");
}
}
(4)线程池
package com.example.test.demo.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(()->{
System.out.println(Thread.currentThread().getName() + "运行了");
});
System.out.println(Thread.currentThread().getName() + "运行了");
}
}
(5)@Async注解方式(注意:需要在启动类上加上@EnableAsync注解)
package com.example.test.demo.thread;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class LogManage {
@Async
public void asyncLog() {
try {
Thread.sleep(3000);
} catch (Exception e) {
}
}
}
2.手写一个实现Spring框架@Async
核心代码
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAsyncAop {
@Around("@annotation(com.example.test.anno.MyAsync)")
public void round (ProceedingJoinPoint joinPoint) {
new Thread(() -> {
try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}).start();
}
}
写在最后:
多线程的应用场景:
1.对于搞web开发的人来说,用户每发一个http请求到后台来,后台要尽量减少用户的请求等待时间,比如发短信、发邮件可以单独另开一个线程去处理
2.比如说保存接口,如果是大批量的保存,可以开启一条线程去处理保存大批量的数据