进程与线程
单进程操作系统:在同一个时间段内只允许有一个程序运行,例如早期的DOS操作系统。
多进程操作系统:在一个CPU、一块资源的情况下,程序利用一些轮转算法,可以让一个资源在一个时间段内同时处理多个不同的程序(进程),但是在一个时间点上只允许有一个进程去执行。
线程:在每一个进程上可以继续划分出若干个线程,那么线程的操作一定是要比进程更快的,所以多线程的操作性能一定会超过多进程的操作。
但是所有的线程都一定要在进程的基础之上进行划分。进程如果一旦消失,线程一定会消失。线程永远要依附于进程存在。
线程的实现
在Java中对于多线程实现一定要有一个线程的主类,而这个线程的主类往往是需要操作一些资源。但是对于多线程主类的实现是有一定要求:
1、继承Thread父类
2、实现Runnable接口(Callable接口)
public class MyThread extends Thread {
private String name;
public MyThread(String name){
this.name=name;
}
@Override
public void run(){
for(int x=0;x<10;x++){
System.out.println(this.name+".x = "+x);
}
}
public static class TestDemo{
public static void main(String args[]){
MyThread mt1= new MyThread("线程A");
MyThread mt2= new MyThread("线程B");
MyThread mt3= new MyThread("线程C");
/*
调用mt1.start()方法,线程是交错执行的,每一次执行结果没有固定的顺序
*/
mt1.start();//启动多线程
mt2.start();//启动多线程
mt3.start();//启动多线程
/*
调用mt1.run()方法,线程是按顺序执行的,A执行完再执行B,每一次执行结果一样;
所以必须用start()方法来启动多线程*/
mt1.run();
mt2.run();
mt3.run();
}
}
}
结论:启动多线程必须调用Thread的start()方法来启动
继承Thread类会产生单继承的局限,最好的做法是实现Runnable接口来完成多线程,以后用的都是实现Runnable接口
以下三种写法效果相同
public class MyThread2 implements Runnable {
private String name;
public MyThread2(String name){
this.name=name;
}
@Override
public void run(){
for(int x=0;x<10;x++){
System.out.println(this.name+".x = "+x);
}
}
// public static class TestDemo{
// public static void main(String args[]){
// MyThread mt1= new MyThread("线程A");
// MyThread mt2= new MyThread("线程B");
// MyThread mt3= new MyThread("线程C");
//
// new Thread(mt1).start();
// new Thread(mt2).start();
// new Thread(mt3).start();
// }
// }
// public static class TestDemo{
// public static void main(String args[]){
// String name="线程对象";
// new Thread(new Runnable() {
// @Override
// public void run() {
// for (int x = 0; x < 10; x++) {
// System.out.println(name + ".x = " + x);
// }
// }
// }).start();
// }
// }
/*JDK 1.8使用Lamda表达式
语法形式为 () -> {},其中 () 用来描述参数列表,{} 用来描述方法体,-> 为 lambda运算符 ,读作(goes to)
*/
public static class TestDemo{
public static void main(String args[]){
String name="线程对象";
new Thread(()->{
for (int x = 0; x < 10; x++) {
System.out.println(name + ".x = " + x);
}
}).start();
}
}
}
Springboot开启多线程
线程池:线程池引入的目的是为了解决:多次使用线程意味着,我们需要多次创建并销毁线程。而创建并销毁线程的过程势必会消耗内存;线程池的好处,就是可以方便的管理线程,也可以减少内存的消耗。
在springboot 提供ThreadPoolTaskExecutor 线程池
Springboot开启多线程需要用到两个注解:@EnableAsync和@Async;
@EnableAsync:在配置类中通过@EnableAsync注解开启对异步任务的支持,让配置类实现AsyncConfigurer接口,并重写getAsyncExecutor方法,并返回一个ThreasPoolTaskExecutor,就可以获取一个基于线程池的TaskExecutor;
@Async:在实际执行的Bean的方法中使用@Async注解来表明这是一个异步任务,用在方法上,表示这个方法是一个异步的方法,如果用在类上面,表明这个类中的所有方法都是异步的方法。
配置类:
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@SpringBootConfiguration
@ComponentScan("com.xxx")//service所在包路径
@EnableAsync //开启异步任务线程
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);//核心线程池数量
executor.setMaxPoolSize(10);//最大线程数量
executor.setQueueCapacity(5);//线程池的队列容量
executor.setThreadNamePrefix("test-executor-");//线程名称的前缀
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//线程池对拒绝任务的处理策略
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
return new SimpleAsyncUncaughtExceptionHandler();
}
}
异步任务:
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
@Service
public class TaskService {
@Async
/**
* 表明是异步调用
* 没有返回值
*/
public void excutVoidTask(int i) {
System.out.println("异步执行任务第[" + i + "] 个");
}
/**
* 有返回值
* 异常调用
*
* @param i
* @return
* @throws InterruptedException
*/
@Async
public Future<String> excuteValueTask(int i) throws InterruptedException {
Thread.sleep(1000);
Future<String> future = new AsyncResult<String>("success is " + i);
System.out.println("异步执行任务第[" + i + "] 个");
return future;
}
}
测试异步任务:
import com.xxx.TaskService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot1ApplicationTests {
@Autowired
private TaskService service;
@Test
public void contextLoads() {
}
/**
* 没有返回值测试
*/
@Test
public void testVoid() {
for (int i = 0; i < 20; i++) {
service.excutVoidTask(i);
}
System.out.println("========主线程执行完毕=========");
}
@Test
public void testReturn() throws InterruptedException, ExecutionException {
List<Future<String>> lstFuture = new ArrayList<>();// 存放所有的线程,用于获取结果
for (int i = 0; i < 100; i++) {
while (true) {
try {
// 线程池超过最大线程数时,会抛出TaskRejectedException,则等待1s,直到不抛出异常为止
Future<String> stringFuture = service.excuteValueTask(i);
lstFuture.add(stringFuture);
break;
} catch (TaskRejectedException e) {
System.out.println("线程池满,等待1S。");
Thread.sleep(1000);
}
}
}
// 获取值.get是阻塞式,等待当前线程完成才返回值
for (Future<String> future : lstFuture) {
System.out.println(future.get());
}
System.out.println("========主线程执行完毕=========");
}
}
参考:https://blog.csdn.net/weixin_39800144/article/details/79046237
Java并发包线程池类ThreadPoolExecutor
在Java并发包中提供了线程池类——ThreadPoolExecutor,实际上更多的我们可能用到的是Executors工厂类为我们提供的线程池:newFixedThreadPool、newSingleThreadPool、newCachedThreadPool,这三个线程池并不是ThreadPoolExecutor的子类,关于这几者之间的关系,我们先来查看ThreadPoolExecutor,查看源码发现其一共有4个构造方法。
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
corePoolSize:核心线程池的线程数量
maximumPoolSize:最大的线程池线程数量
keepAliveTime:线程活动保持时间,线程池的工作线程空闲后,保持存活的时间。
unit:线程活动保持时间的单位。
workQueue:指定任务队列所使用的阻塞队列
①首先会判断核心线程池里是否有线程可执行,有空闲线程则创建一个线程来执行任务。
②当核心线程池里已经没有线程可执行的时候,此时将任务丢到任务队列中去。
③如果任务队列(有界)也已经满了的话,但运行的线程数小于最大线程池的数量的时候,此时将会新建一个线程用于执行任务,但如果运行的线程数已经达到最大线程池的数量的时候,此时将无法创建线程执行任务。
所以实际上对于线程池不仅是单纯地将任务丢到线程池,线程池中有线程就执行任务,没线程就等待。
回到ThreadPoolExecutor,首先来看它的继承关系:
ThreadPoolExecutor它的顶级父类是Executor接口,只包含了一个方法——execute,这个方法也就是线程池的“执行”。
//Executor#execute
public interface Executor {
void execute(Runnable command);
}
实际应用代码中案例:
/** 线程池相关配置常量 */
private AtomicInteger count = new AtomicInteger(0);
private final static int CORE = 20;
private final static int MAX = 40;
private final static int KEEP = 10;
private ThreadPoolExecutor threadExecutor = new ThreadPoolExecutor(CORE, MAX, KEEP, TimeUnit.MINUTES, new ArrayBlockingQueue<>(100), r -> {
Thread t = new Thread(r);
t.setName(ScmItemCommissionService.class.getSimpleName() + " - " + count.addAndGet(1));
return t;
}
```
同步商品:
```
@Override
public PyRpcResult<Integer> syncItemByIds(List<Long> ids) {
if (CollectionUtils.isEmpty(ids)) {
return PyRpcResult.failure("主键为空");
}
// 线程执行
for (Long id : ids) {
executor.execute(() -> {
ItemBO itemBo = ItemService.getById(id);
if (Objects.isNull(itemBo)) {
return;
}
try {
SyncService.syncById(itemBo.getItemId(), SyncIdTypeEnum.GOODS.getNum());
} catch (Exception e) {
log.error("批量同步商品异常,id={}", id, e);
}
});
}
return PyRpcResult.success(ids.size());
}
参考:https://www.cnblogs.com/yulinfeng/p/7021293.html
JVM与多线程
每当使用java命令在JVM上解释某一个程序执行的时候,都会默认启动一个JVM的进程,而主方法只是进程中的一个线程,所以整个程序一直都跑在线程的运行机制上。
每一个JVM至少会启动两个线程:主线程、GC线程
public static class TestDemo{
public static void main(String args[]){
String name="线程对象";
new Thread(()->{
for (int x = 0; x < 10; x++) {
System.out.println(name + Thread.currentThread().getName()+".x = " + x);
}
}).start();
System.out.println("线程A"+Thread.currentThread().getName());
System.out.println("线程B"+Thread.currentThread().getName());
}
}
输出
线程Amain
线程Bmain
线程对象Thread-0.x = 0
线程对象Thread-0.x = 1
线程对象Thread-0.x = 2
线程对象Thread-0.x = 3
线程对象Thread-0.x = 4
线程对象Thread-0.x = 5
线程对象Thread-0.x = 6
线程对象Thread-0.x = 7
线程对象Thread-0.x = 8
线程对象Thread-0.x = 9
线程的休眠
public static void sleep(long millis) throws InterruptedException
被其他的线程中断
线程的同步与死锁
多个线程操作时,必须考虑到资源的同步问题(比如卖票问题)
实现同步操作:
每一个线程要执行卖票时,其他线程应当等待当前线程执行完毕后才可以进入。这时候就引入了“锁”
如果要想在若干行代码上实现锁,那么就需要使用同步代码块或同步方法来解决。
同步代码块:使用synchronized关键字定义的代码块就称为同步代码块,但是在进行同步的时候需要设置有一个同步对象,那么可以使用this同步当前对象。
private int ticket=500;
@Override
public void run() {
for(int x=0;x<10;x++) {
synchronized(this) {//同步代码块
if (this.ticket > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ".ticket=" + this.ticket--);
}
}
}
但是加入同步之后整个代码的执行速度已经变慢了,而且不像没有使用同步时,多个线程会一起进入到方法之中。
异步的执行速度要快于同步的执行速度,但是异步的操作属于非线程安全的操作。而同步操作属于线程的安全操作(操作数据时数据不会出错)
同步方法:使用public synchronized void XX(){}
对于同步操作,除了用于代码块定义外,也可以在方法上定义同步操作。
public class TicketSale implements Runnable {
private int ticket=500;
@Override
public void run() {
for(int x=0;x<1000;x++) {
this.sale();
}
}
public synchronized void sale(){
if (this.ticket > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ".ticket=" + this.ticket--);
}
}
public static void main(String[] args) throws Exception{
TicketSale mt = new TicketSale();
Thread t1 = new Thread(mt,"票贩子A");
Thread t2 = new Thread(mt,"票贩子B");
Thread t3 = new Thread(mt,"票贩子C");
t1.start();
t2.start();
t3.start();
}
}
在多个线程访问同一资源时一定要考虑到数据的同步问题,同步就使用synchronized
线程死锁
死锁是一种不确定的状态,对于死锁的操作应该出现的越少越好。
请问多线程访问同一资源时可能带来什么问题?以及会产生什么样的附加问题?
多个线程访问同一资源时必须要考虑同步,可以使用synchronized定义同步代码块或同步方法。
程序中如果出现过多的同步那么久将产生死锁。
出现了synchronized说明是同步,线程安全的,但是性能一定不高