python 多线程学习-1
多任务的概念
操作系统可以同时运行多个任务,参考任务管理器
原理是操作系统轮流让各个任务交替执行,每个任务在CPU上执行很短的时间,因为CPU的执行速度快,就像同时执行一样
并发
指的是任务数多余cpu核数,通过操作系统的各种任务调度算法,实现用多个任务在同一时 间段执行(实际上总有一些任务不在执行,因为切换任务的速度相当快,看上去一起执行而已)
并行
指的是多核cpu情况下,多个任务的一些任务往往是在同一时间点执行的
单线程
import time
def thread1():
print("线程1")
time.sleep(1)
def main():
for i in range(1,10):
thread1()
main()
运行结果
多单线程
def thread1():
print("线程1")
time.sleep(1)
def main():
for i in range(1,10):
t=threading.Thread(target=thread1)
t.start()
main()
当多线程时,可以明显感觉到控制台输出花费时间要短很多
在多线程中只有start()时才会创建线程并且开始执行
import threading
import time
def thread1():
print("线程1")
time.sleep(1)
def thread2():
print("线程2")
time.sleep(2)
def thread3():
print("线程3")
time.sleep(10)
def main():
print('-----开始-----:%s'%time.ctime())
t1=threading.Thread(target=thread1)
t2=threading.Thread(target=thread2)
t3=threading.Thread(target=thread3)
t1.start()
t2.start()
t3.start()
time.sleep(5)
print('\n-----结束-----:%s'%time.ctime())
main()
程序会等待所有的子线程结束后才结束
查看线程数量
import threading
import time
def thread1():
for i in range(3):
print("线程1"+" "+str(i))
time.sleep(1)
print("\n线程1"+" "+str(i)+"结束")
def thread2():
for i in range(4):
print("线程2"+" "+str(i))
time.sleep(2)
print("\n线程2"+" "+str(i)+"结束")
def thread3():
for i in range(5):
print("线程3"+" "+str(i))
time.sleep(3)
print("\n线程3"+" "+str(i)+"结束")
def main():
print('-----开始-----:%s'%time.ctime())
t1=threading.Thread(target=thread1)
t2=threading.Thread(target=thread2)
t3=threading.Thread(target=thread3)
t1.start()
t2.start()
t3.start()
while True:
length=len(threading.enumerate())
print("\n当前运行线程数%d"%length)
if length<=1:
break
time.sleep(0.5)
print('\n-----结束-----:%s'%time.ctime())
main()
线程共4个 一个主线程+3个子线程,程序会等待所有的子线程结束后才结束
线程类的封装
import threading
import time
class Thread_1(threading.Thread):
def run(self):
for i in range(1,10):
time.sleep(1)
print("Thread:"+self.name+" "+str(i)+"\n")
t=Thread_1()
t.start()
封装线程类时需要复写run()方法,而不是一般类里的 init() 方法
线程类的顺序
import threading
import time
class Thread_1(threading.Thread):
def run(self):
for i in range(1,10):
time.sleep(1)
print("Thread:"+self.name+" "+str(i)+"\n")
class Thread_2(threading.Thread):
def run(self):
for i in range(1,10):
time.sleep(1)
print("Thread:"+self.name+" "+str(i)+"\n")
class Thread_3(threading.Thread):
def run(self):
for i in range(1,10):
time.sleep(1)
print("Thread:"+self.name+" "+str(i)+"\n")
t1=Thread_1()
t2=Thread_2()
t3=Thread_3()
t1.start()
t2.start()
t3.start()
多线程程序的执行顺序是不确定的,只能保证每个线程都运行完整个run函数,但是线程的启动顺序、run 函数中每次循环的执行顺序都不能确定。