大家好,我是天空之城,今天給大家帶來,多線程的創建與查看,這是爲後面利用多線程做爬蟲做準備的。
1. 多任務基本介紹
有很多的場景中的事情是同時進行的,比如開車的時候 手和腳共同來駕駛汽車,再比如唱歌跳舞也是同時進行的
1.1 程序中模擬多任務
2. 主線程和子線程的執行關係
• 主線程會等待子線程結束之後在結束
• join() 等待子線程結束之後,主線程繼續執行
• setDaemon() 守護線程,不會等待子線程結束
3.threading.enumerate() 查看當前線程的數量
4. 驗證子線程的執行與創建
當調用Thread的時候,不會創建線程。
當調用Thread創建出來的實例對象的start方法的時候,纔會創建線程以及開始運行這個線程。
繼承Thread類創建線程
import threading
import time
class A(threading.Thread):
def __init__(self,name):
super().__init__(name=name)
def run(self):
for i in range(5):
print(i)
if __name__ == "__main__":
t = A('test_name')
t.start()
5. 線程間的通信(多線程共享全局變量)
在一個函數中,對全局變量進行修改的時候,是否要加global要看是否對全局變量的指向進行了修改,如果修改了指向,那麼必須使用global,僅僅是修改了指向的空間中的數據,此時不用必須使用global
線程是共享全局變量
5.1 多線程參數-args
threading.Thread(target=test, args=(num,))
----------------------------------------------------------------
1.多線程的創建
import threading
import time
def singe():
for i in range(3):
print('正在唱歌....')
time.sleep(1)
def dance():
for i in range(3):
print('正在跳舞....')
time.sleep(1)
def main():
t1 = threading.Thread(target=singe)
t2 = threading.Thread(target=dance)
t1.start()
t2.start()
if __name__ == '__main__':
# singe()
# dance()
main()
# def demo():
#
# for i in range(5):
# print('hello world')
#
# time.sleep(1)
#
#
# if __name__ == '__main__':
#
#
#
#
# t = threading.Thread(target=demo)
# # 守護線程 不會等待子線程結束
# t.setDaemon(True)
# t.start() # 啓動線程 主線程會等待子線程結束之後 主線程在結束
# # join() 等待子線程結束之後,主線程繼續執行
# # t.join()
# time.sleep(5)
# print(1)
2.子線程的創建與執行
import time
import threading
def demo():
for i in range(5):
print('demo--%d'% i)
def main():
print(threading.enumerate())
t1 = threading.Thread(target = demo) #
print(threading.enumerate())
# 創建線程和開啓線程都是通過t.start() 面試題
t1.start() # 啓動?
print(threading.enumerate())
if __name__ == '__main__':
main()
3.查看線程的數量
import threading
import time
def demo1():
for i in range(5):
print('demo1--%d'%i)
time.sleep(1)
def demo2():
for i in range(10):
print('demo2--%d' % i)
time.sleep(1)
def main():
t1 = threading.Thread(target=demo1,name = 'demo1')
t2 = threading.Thread(target=demo2,name = 'demo2')
t1.start()
t2.start()
while True:
print(threading.enumerate())
if len(threading.enumerate()) <= 1:
break
time.sleep(1)
if __name__ == '__main__':
main()
4.通過類來創建線程
import threading
import time
class Main(threading.Thread):
def run(self):
for i in range(5):
print(i)
if __name__ == '__main__':
# main()
m = Main()
m.start()
5.線程間的通信
# global
# a = 20
#
#
# def fn():
#
# global a
# a = 80
# print('函數內部a:',a)
#
# fn()
#
# print('函數外部a:',a)
import threading
import time
# 線程間是共享的全局變量
# num = 100
num = [11,22]
def demo1(nums):
# global num
#
# num += 1
num.append(nums)
print('demo1--%s'% str(num))
def demo2():
print('demo2--%s' % str(num))
def main():
t1 = threading.Thread(target = demo1,args=(33,))
t2 = threading.Thread(target = demo2)
t1.start()
time.sleep(1) # 保證demo1先執行
t2.start()
print('main-num=%s'% str(num))
if __name__ == '__main__':
main()
6.線程小遊戲,來挑選你的夢中女神吧。。
# 1.有12個備選選項和2個功能按鈕 確定備選選項和功能按鈕的位置
# 2.點擊開始會不斷旋轉。選中的時候背景顏色爲紅色,點擊停止結束
import threading
import tkinter
import time
# 1.實現窗口
root = tkinter.Tk()
root.title('美女聯盟')
root.minsize(300,300)
# 2 擺放按鈕
btn1 = tkinter.Button(root, text='蒼老師', bg='red')
btn1.place(x=20, y=20, width=50, height=50)
btn2 = tkinter.Button(root, text='趙雅芝', bg='white')
btn2.place(x=90, y=20, width=50, height=50)
btn3 = tkinter.Button(root, text='李若彤', bg='white')
btn3.place(x=160, y=20, width=50, height=50)
btn4 = tkinter.Button(root, text='范冰冰', bg='white')
btn4.place(x=230, y=20, width=50, height=50)
btn5 = tkinter.Button(root, text='趙薇', bg='white')
btn5.place(x=230, y=90, width=50, height=50)
btn6 = tkinter.Button(root, text='林青霞', bg='white')
btn6.place(x=230, y=160, width=50, height=50)
btn7 = tkinter.Button(root, text='朱茵', bg='white')
btn7.place(x=230, y=230, width=50, height=50)
btn8 = tkinter.Button(root, text='張曼玉', bg='white')
btn8.place(x=160, y=230, width=50, height=50)
btn9 = tkinter.Button(root, text='劉巖', bg='white')
btn9.place(x=90, y=230, width=50, height=50)
btn10 = tkinter.Button(root, text='劉詩詩', bg='white')
btn10.place(x=20, y=230, width=50, height=50)
btn11 = tkinter.Button(root, text='高圓圓', bg='white')
btn11.place(x=20, y=160, width=50, height=50)
btn12 = tkinter.Button(root, text='鄧紫棋', bg='white')
btn12.place(x=20, y=90, width=50, height=50)
#2.1將所有的選項放到列表中 目的:爲了操作這些選項
hero_list = [btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btn10,btn11,btn12]
# 定義一個標記
stop_sign = False # 默認是停止
stop_id = None
# 3 定義一個函數 1.循環備選選項 2.設置選項顏色
def round():
global stop_id
i = 1
if isinstance(stop_id,int):
i = stop_id
while True:
time.sleep(0.3)
for x in hero_list:
x['bg'] = 'white'
hero_list[i]['bg'] = 'red'
i += 1
print('當前的i爲:',i)
if i >= len(hero_list):
i = 0
if stop_sign == True:
stop_id = i
break
# 4 定義停止的方法
def stop():
global stop_sign
if stop_sign == True:
return
stop_sign = True
# 5 定義開始的方法
def newtask():
global stop_sign
stop_sign = False
t = threading.Thread(target=round)
t.start()
# 6.設置按鈕
btn_start = tkinter.Button(root,text='開始',command=newtask)
btn_start.place(x=90,y=125,width=50,height=50)
btn_stop = tkinter.Button(root,text='停止',command=stop)
btn_stop.place(x=160,y=125,width=50,height=50)
# 顯示窗口
root.mainloop()