您的位置:首页 > 编程语言 > Python开发

python简单多线程

2016-03-03 22:38 696 查看
#coding=utf-8

import threading
import random
from time import sleep

def task1():
print(threading.current_thread().getName() + " start.")
for i in range(5):
print("i: " + str(i))
sleep(1)
print(threading.current_thread().getName() + " done!")

def task2():
print("task second start.")
for i in range(5):
print("rand: " + str(random.randint(10,20)))    ##output random num
sleep(1)
print("task second done!");

def main():
print("main thread start: ")
threads = []	#create a list of thread
t1 = threading.Thread(target=task1,name="task first")
t2 = threading.Thread(target=task2)
threads.append(t1)
threads.append(t2)

for t in threads:
t.start()
for t in threads:
t.join()
print("muti-thread done!")

###mian fun
main()

输出结果:

E:\MySelf\myfile\My Python>thread.py
main thread start:
task first start.
i: 0
task second start.
rand: 13
i: 1
rand: 10
i: 2
rand: 14
rand: 19
i: 3
rand: 13
i: 4
task first done!
task second done!
muti-thread done!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程 python