线程和进程是什么:
线程:进程中的每个子任务,不能独立存在,CPU执行的最小单位
进程:独立的所有子任务的集合
线程,进程:目的都是想同时完成任务
线程和进程的特点:
线程的特点:依赖进程(内存共享,CPU使用独立)启动开销小,线程之间共享数据容易,方便通信,线程不安全。
进程的特点:独立(内存独立,CPU使用独立)启动进程开销大(速率低),进程之间很难共享数据,和数据通信,数据安全高。
python包:
现在python3通用threading
threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法:
threading.currentThread(): 返回当前的线程变量。
threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:
run(): 用以执行线程活动的方法。
start():启动线程活动使线程达到一个就绪状态
join([time]):强制调用某个线程进入执行状态,本线程礼让CPU资源,进入阻塞,休眠状态,直至某个线程退出/抛异常/超时 本线程才进入就绪状态 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
isAlive(): 返回线程是否活动的。
getName(): 返回线程名。
setName(): 设置线程名。
例一:
import threading print([x for x in range(9)]) thread = threading.current_thread() thread.setName('主线程mmm') print('线程名称:' , thread.getName()) print('正在运行的线程:',threading.enumerate()) print('正在运行的线程个数:',threading.activeCount())
打印结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
线程名称: 主线程mmm正在运行的线程: [<_MainThread(主线程mmm, started 19204)>]
正在运行的线程个数: 1
实现线程的两种方式:类方法 & 函数方法
线程类:
1.继承threading.Thread
2.写构造方法,且必须调用父类的构造方法
3.重写父类的run方法,会在start之后自动调用
4.实现开始方法,如果重写了start()方法,一定要调用父类的start()
需要调用start()方法才可以执行
#class 类方法实现线程 import threading,time class Mythread(threading.Thread): def __init__(self): threading.Thread.__init__(self) print('Mythread init...') def run(self): for i in range(6): print(self.getName(),i) time.sleep(1) t1 = Mythread() t2 = Mythread() t1.start() t2.start()
打印结果:
Mythread init...
Mythread init...
Thread-1 0
Thread-2 0
Thread-1 1
Thread-2 1
Thread-1 2
Thread-2 2
Thread-1 3
Thread-2 3
Thread-1 4
Thread-2 4
Thread-1 5
Thread-2 5
简易的抢票的线程:
import threading, time nums = 50 count = 0 class Ticket(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.setName(name) def run(self): global nums, count while True: if nums ==0: return else: nums = nums - 1 count = count + 1 print('{0} 抢到了第 {1} 张票,还剩 {2} 张'.format(self.getName(),count,nums )) time.sleep(1) if __name__ == '__main__': t1 = Ticket('黄牛') t2 = Ticket('手机') t3 = Ticket('电脑') t1.start() t2.start() t3.start()
函数方法:
import threading import time num = 50 def something(x): for i in range(1,10): global num num += i print(x,num) time.sleep(0.2) new_threading1 = threading._start_new_thread(something,('张三',)) new_threading2 = threading._start_new_thread(something,('李四',)) input() #input的作用是,不让主线程结束,这样子线程还可以正常跑自己用函数的方法改造了一下上面的抢票代码,非常简单的一个
import threading,time num = 50 count = 0 def Ticket(name): while True: global num, count if num > 0: num -= 1 count += 1 print(name,'抢到票NO.',count,'还剩下:',num,'张票') time.sleep(0.2) else: print('结束吧!') break t1 = threading.Thread(target=Ticket, args=('小王',)) t2 = threading.Thread(target=Ticket, args=('小李',)) t1.start() t2.start()