程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Python >> Python模塊學習之threading多線程

Python模塊學習之threading多線程

編輯:Python

創建了一個threadOne類,它繼承了threading.Thread,重寫了從父類繼承的run方法,start()方法用於啟動線程,run()方法將在線程開啟後執行,

import threading
import time
class threadOne(threading.Thread):
"""docstring for threadOne"""
def __init__(self, num,name):
super(threadOne, self).__init__()
self.name = name
self.num = num
def run(self):
print self.name+'doing:...'

if __name__ == '__main__':
for i in xrange(5):
t = threadOne(i,'thread-'+str(i))
t.start()
time.sleep(2) #確保線程都執行完畢
#output#
#並行執行的
thread-0doing:...thread-1doing:...

thread-2doing:...thread-3doing:...

thread-4doing:...


join(timeout)
可以一個線程可以等待另一個線程執行結束後再繼續運行。通過設置timeout,可以避免無休止的等待

import threading
import time
class threadOne(threading.Thread):
"""docstring for threadOne"""
def __init__(self, num,name):
super(threadOne, self).__init__()
self.name = name
self.num = num
def setT(self,time):
self.time = time
def run(self):
print '%s will work %d seconds' %(self.name,self.time)
time.sleep(self.time)
print '%s have finished!' %(self.name)

if __name__ == '__main__':
tasks = []
for i in xrange(1,5):
t = threadOne(i,'thread_:'+str(i))
t.setT(i)
t.start()
tasks.append(t)

print 'main thread waiting for exit...'

for t in tasks:
t.join(1)

print 'main thread have finished!'


#output#
thread_:1 will work 1 secondsthread_:2 will work 2 seconds

thread_:3 will work 3 secondsthread_:4 will work 4 seconds
main thread waiting for exit...

thread_:1 have finished!
thread_:2 have finished!
thread_:3 have finished!
main thread have finished! #there thread_:4 not wait
thread_:4 have finished!

setDaemon()
默認主進程會在所有的子進程結束後自動退出,如果設置setDaemon則主線程在退出時會結束所有的子進程

import threading
import time
class threadOne(threading.Thread):
"""docstring for threadOne"""
def __init__(self, num,name):
super(threadOne, self).__init__()
self.name = name
self.num = num
def setT(self,time):
self.time = time
def run(self):
print '%s will work %d seconds' %(self.name,self.time)
time.sleep(self.time)
print '%s have finished!' %(self.name)

if __name__ == '__main__':
print 'main thread waiting for exit...'

for i in xrange(1,5):
t = threadOne(i,'thread_:'+str(i))
t.setT(i)
t.setDaemon(True)
t.start()

#main thread processing
time.sleep(1)
print 'main thread have finished!'

#output#
main thread waiting for exit...
thread_:1 will work 1 secondsthread_:2 will work 2 seconds
thread_:4 will work 4 secondsthread_:3 will work 3 seconds
thread_:1 have finished!
main thread have finished! #only thread_1 working other not work

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved