python 多线程
_thread
import _thread
#_thread.start_new_thread ( function, args[, kwargs] )
import _thread
import time
# 为线程定义一个函数
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
# 创建两个线程
try:
_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print ("Error: 无法启动线程")
while 1:
pass
threading
Thread类提供了以下方法:
run(): 用以表示线程活动的方法。
start():启动线程活动。
join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
isAlive(): 返回线程是否活动的。
getName(): 返回线程名。
setName(): 设置线程名。
from threading import Thread
import threading
from time import ctime,sleep
def music(func):
for i in range(2):
print "I was listening to %s. %s" %(func,ctime())
sleep(1)
def move(func):
for i in range(2):
print "I was at the %s! %s" %(func,ctime())
sleep(5)
threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
print "all over %s" %ctime()
多线程返回值
- 复写Thread类,自定义一个get_result()方法
from threading import Thread
# _sum = 0
def cal_sum(begin, end):
# global _sum
_sum = 0
for i in range(begin, end + 1):
_sum += i
return _sum
"""重新定义带返回值的线程类"""
class MyThread(Thread):
def __init__(self, func, args):
super(MyThread, self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
if __name__ == '__main__':
t1 = MyThread(cal_sum, args=(1, 5))
t2 = MyThread(cal_sum, args=(6, 10))
t1.start()
t2.start()
t1.join()
t2.join()
res1 = t1.get_result()
res2 = t2.get_result()
print(res1 + res2)
- 使用全局变量
from threading import Thread
_sum = 0
def cal_sum(begin, end):
# 声明使用全局变量
global _sum
for i in range(begin, end + 1):
_sum += i
if __name__ == '__main__':
t1 = Thread(target=cal_sum, args=(1, 5))
t2 = Thread(target=cal_sum, args=(6, 10))
t1.start()
t2.start()
print(_sum)