标签:影响 时间 port 没有 start get imp odi 线程创建
一、使用threading模块多线程执行
start()
方法来启动#coding=utf-8 import threading import time def test(): print("----TEST By SQYY----") time.sleep(1) if __name__ == "__main__": for i in range(5): t = threading.Thread(target=test) t.start() #启动线程,即让线程开始执行
以上代码运行结果
----TEST By SQYY--------TEST By SQYY--------TEST By SQYY---- ----TEST By SQYY--------TEST By SQYY----
二、使用Thread子类完成创建多线程
如果多个线程执行的都是同一个函数,各自之间不会有影响
主线程等待所有子进程结束之后才结束
#coding=utf-8 import threading import time class MyThread(threading.Thread): def run(self) for i in range(3): time.sleep(1) msg = "I‘m" + self.name + ‘@‘ + str(i) #name属性中保存的是当前线程的名字 print(msg) if __name__ ==‘__main__‘: t = MyThread() t.start()
以上代码运行结果:
I‘m Thread-1 @0 I‘m Thread-1 @1 I‘m Thread-1 @2
三、线程的执行顺序
#coding=utf-8 import threading import time class MyThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) msg = "I‘m "+self.name+‘ @ ‘+str(i) print(msg) def test(): for i in range(5): t = MyThread() t.start() if __name__ == ‘__main__‘: test()
以上代码运行结果:
I‘m Thread-1 @ 0 I‘m Thread-2 @ 0 I‘m Thread-5 @ 0 I‘m Thread-3 @ 0 I‘m Thread-4 @ 0 I‘m Thread-3 @ 1 I‘m Thread-4 @ 1 I‘m Thread-5 @ 1 I‘m Thread-1 @ 1 I‘m Thread-2 @ 1 I‘m Thread-4 @ 2 I‘m Thread-5 @ 2 I‘m Thread-2 @ 2 I‘m Thread-1 @ 2 I‘m Thread-3 @ 2
四、多线程全局变量共享
from threading import Thread import time #线程之间共享全局变量 g_num = 100 def work1(): global g_num for i in range(3): g_num += 1 print("----in work1, g_num is %d---"%g_num) def work2(): global g_num print("----in work2, g_num is %d---"%g_num) print("---线程创建之前g_num is %d---"%g_num) t1 = Thread(target=work1) t1.start() #延时一会,保证t1线程中的事情做完 time.sleep(1) t2 = Thread(target=work2) t2.start()
以上代码运行结果:
---线程创建之前g_num is 100--- ----in work1, g_num is 103--- ----in work2, g_num is 103---
标签:影响 时间 port 没有 start get imp odi 线程创建
原文地址:http://www.cnblogs.com/sqyysec/p/7287237.html