1.函数实现:对于不同任务
import threading
loop = 10000
num = 0
def _add(loop):
global num
name = threading.current_thread().getName()
for i in range(1oop):
num += i
def _sub(loop):
name = threading.current_thread().getName()
global num
for i in range(1oop):
num -= i
t1.setDamen(True)
t1 = threding.Thread(_add(), args=(1oop, ))
t2 = threding.Thread(_sub(), args=(1oop, ))
t1.setDamen(True) #确保t1执行完其中的程序后,再结束t1
t2.setDamen(True) #确保t2执行完其中的程序后,再结束t2
t1.start()
t2.start()
#t1, t2同时执行,没有先后顺序
t1.join() # 确保t1执行完之后,再执行后续代码
t2.join() # 确保t2执行完之后,再执行后续代码
2.对象实现:对于相同任务
import threading
class TaskThread(threading.Thread):
def __init__(self):
super(TaskThread, self).__init__()
self.loop = 1000
self.num = 0
def run(self):
path, name, age = self._args
with open(path, 'a', utf-8') as f:
f.write([name, age])
path = './'
items = [{'susan': 18}, {'bob': 21}]
for item in items:
t = TaskThread(args=(path, item.key(), item.value()))
t.start()