1.線程是最小的進程
2.在python中使用線程需要引入 threading包
3.引入線程最重要的是小心高併發的問題
4.解決高併發的問題可以嘗試使用鎖的概念
直接上代碼:
一.創建線程:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
def job():
time.sleep(1)
print "正在執行任務"
print "當前線程的個數",threading.active_count()
print "當前線程信息",threading.current_thread()
if __name__ == "__main__":
#運行函數
#job()
#創建線程,並執行
t1 = threading.Thread(target = job ,name = "job1" ,args=())
t2 = threading.Thread(target = job ,name = "job221" ,args=())
#開始線程
t1.start()
t2.start()
二.多個線程
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
def readBook(name):
time.sleep(1)
print "馬化騰正在讀",name
def listenMusic(name):
time.sleep(2)
print "三毛正在聽",name
if __name__=="__main__":
t1 = threading.Thread(target = readBook,name = readBook, args=("水滸傳",))
t2 = threading.Thread(target = listenMusic,name = listenMusic ,args=("小哪吒",))
t1.start()
t2.start()
# join方法: 在使用多線程時,會等使用該方法的待線程結束之後,再執行其他線程,作用就是阻塞正在調用的其它線程。
t1.join()
t2.join()
print (time.ctime())
三.繼承加線程
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
class Job(threading.Thread):
def __init__(self,jobname):
super(Job,self).__init__()
self.jobname = jobname
def run(self):
print "this is Chinese air"
t1 = Job(jobname = "jinwanchisaokao")
t1.start()
四.線程守護
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
def readBook(name):
time.sleep(1)
print "馬化騰正在讀",name
def listenMusic(name):
time.sleep(2)
print "三毛正在聽",name
if __name__=="__main__":
t1 = threading.Thread(target = readBook, args=("水滸傳",))
t2 = threading.Thread(target = listenMusic,args=("小哪吒",))
# 將t1線程生命爲守護線程, 如果設置爲True, 子線程啓動, 當主線程執行結束, 子線程也結束
# 設置setDaemon必須在啓動線程之前進行設置
#設置一個爲false都不行
t1.setDaemon(True)
#t2.setDaemon(True)
t1.start()
t2.start()
#t1.join()
#t2.join()
print (time.ctime())
五.多線程和單線程區別
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
def job(li):
sum(li)
#print li
def use_thread():
li = range(1,10000)
for i in range(5):
t = threading.Thread(target=job, args=(li, ))
t.start()
def use_no_thread():
li = range(1, 10000)
for i in range(5):
job(li)
if __name__ == "__main__":
use_thread()
#use_no_thread()
六.線程鎖
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
def add(lock):
# 操作變量之前進行加鎖
lock.acquire()
global money
for i in range(10000000):
money +=1
#操作變量完成後進行解鎖
lock.release()
def reduce(lock):
lock.acquire()
global money
for i in range(10000000):
money -=1
lock.release()
if __name__=="__main__":
money = 0
#實例化一個鎖對象
lock = threading.Lock()
t1 = threading.Thread(target = add ,args = (lock,))
t2 = threading.Thread(target = reduce , args = (lock,))
t1.start()
t2.start()
t1.join()
t2.join()
print 'monet',money
七.線程加隊列
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
from queue import Queue
#1.理論上多線程執行任務, 會產生一些數據, 爲其他程序執行作鋪墊;
#2. 多線程是不能返回任務執行結果的, 因此需要一個容器來存儲多線程產生的數據
#3. 這個容器如何選擇? list(棧, 隊列), tuple(x), set(x), dict(x), 此處選擇隊列來實現
def job(l,queue):
queue.put(sum(l))
def use_thread():
q = Queue()
threads = []
list1 = [[1, 5, 7, 3, 6, 2], [5, 23, 4, 6], [7, 8, 93, 2], [1, 2, 3, 4]]
for l in list1:
t = threading.Thread(target = job , args=(l,q))
threads.append(t)
t.start
[thread.join() for thread in threads]
#從隊列中拿出所有的運行結果
result = [q.get for _ in range(len(list1))]
print result
if __name__ == "__main__":
use_thread()