python多執行緒例項

2021-07-05 02:03:37 字數 2200 閱讀 9615

a、建立乙個thread的例項,傳給他乙個函式

import threading

from time import sleep

def thread_body(arg1,arg2):

print "i am a child thread",arg1,arg2

sleep(10)

print "end child thread"

def main():

print "____main_____start:"

thread_target=threading.thread(target=thread_body,args=("hello","test"))

print "child start"

thread_target.start()

print "i am main thread"

thread_target.join()

print "end_main"

if __name__=='__main__':

main()

b、建立乙個thread的例項、傳給他乙個可以呼叫的類物件

import threading

from time import sleep

def thread_body(arg1,arg2):

print "i am a child thread",arg1,arg2

sleep(10)

print "end child thread"

class thread_class(object):

def __init__(self,func,args,name=''):

self.func=func

self.name=name

self.args=args

def __call__(self):

def main():

print "____main_____start:"

# thread_target=threading.thread(target=thread_body,args=("hello","test"))

thread_target=threading.thread(target=thread_class(thread_body,("hello",'world'),"child_test"))

print "child start"

thread_target.start()

print "i am main thread"

thread_target.join()

print "end_main"

if __name__=='__main__':

main()

c、從thread派生出乙個子類、建立乙個子類的例項。

import threading

from time import sleep

def thread_body(arg1,arg2):

print "i am a child thread",arg1,arg2

sleep(2)

print "end child thread"

class thread_child(threading.thread):

def __init__(self,func,args,name=''):

threading.thread.__init__(self)

self.name=name

self.args=args

self.func=func

def getresult(self):

return self.res

def run(self):

print 'child run'

def main():

print "____main_____start:"

thread_target=thread_child(thread_body,("hello","world"),"test")

print "child start"

thread_target.start()

print "i am main thread"

thread_target.join()

print "end_main"

python多執行緒例項

import threading import time class mythread threading.thread def init self,n super mythread,self init self.n n def run self print runnint task self.n ...

python多執行緒採集例項

python多執行緒採集例項 python作為一種流行的指令碼程式語言,其功能的強大自然不言而喻,豆瓣網就是使用python開發的,另外很多的it公司了在使用python,也充分說明了python的強大,下面是python多執行緒採集例項 python多執行緒採集例項 coding gb2312 a...

Python簡單多執行緒例項

剛剛學習了python的多執行緒,為了測試多執行緒對處理資料的影響,自己寫了乙個簡單的例項實踐一下多執行緒 coding utf 8 python多執行緒例項 import threading import datetime import time defhandleurllista 執行緒a 如果...