1.协程 async await(挂起,让这段代码自己执行去)
使用协程时,需要其底层方法实现时就是协程,才会生效,否则协程不生效!
因此这边需要先查询哪些方法能够使用协程
import aiohttp
async def get_url(url):
client = aiohttp.ClientSession()
try:
resp = await client.get(url)
await client.close()
return resp
except:
await client.close()
return traceback.format_exc()
import asyncio
import aiomysql.sa as aio_sa
++++++++++++++++++++++++++++++++++
async def main():
# 创建一个异步引擎
engine = await aio_sa.create_engine(host="xx.xxx.xx.xxx",
port=3306,
user="root",
password="root",
db="_hanser",
connect_timeout=10)
# 通过 engine.acquire() 获取一个连接
async with engine.acquire() as conn:
# 异步执行, 返回一个 <class 'aiomysql.sa.result.ResultProxy'> 对象
result = await conn.execute("SELECT * FROM girl")
# 通过 await result.fetchone() 可以获取满足条件的第一条记录, 一个 <class 'aiomysql.sa.result.RowProxy'> 对象
data = await result.fetchone()
协程在有多个io需求的情况下是好用的,不需要依次执行io。就比方说要访问两个网站获取内容后合并或比较,这个时候没有顺序关系,用协程就很好。
2.守护线程
所谓守护线程就是一个主线程的监控者或者说扫尾的。
比方说在一个线程执行过程中可能出现一些错误,守护线程可以专门独立出来处理这些错误,更具代表性的是垃圾回收(GC)。
package com.li.changGe.multithreading.threadState;
public class DaemonDemo01 {
public static void main(String[] args) {
/**
* 播放器线程始终守护着视频线程
*
* player.setDaemon(true);
* 设置播放器线程为守护线程
*/
Thread player = new Thread(() -> {
System.out.println("播放器打开了");
while (true){
System.out.println("播放器进行中");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//while
});
Thread video = new Thread(() -> {
System.out.println("视频打开了");
for (int i = 0; i < 3; i++) {
System.out.println("看视频中");
}
System.out.println("视频关闭了");
});
/**
* 默认为false用户线程
*/
player.setDaemon(true);
player.start();
video.start();
}
}