- Demo1
import threading
import time
def say():
time.sleep(2)
print("我是子线程",time.strftime('%Y-%m-%d %H:%M:%S'))
if __name__ == "__main__":
for i in range(3):
t = threading.Thread(target=say)
t.start()
print("我是主线程",time.strftime('%Y-%m-%d %H:%M:%S'))
日志:
我是主线程 2018-01-26 16:39:18
我是子线程 2018-01-26 16:39:20
我是子线程 2018-01-26 16:39:20
我是子线程 2018-01-26 16:39:20
Process finished with exit code 0
- Demo2 :子线程互不干扰 Join()堵塞主线程
import threading
from time import sleep, ctime
def sign():
for i in range(3):
print('dosomething1...%d' % i)
sleep(1)
print('sign end')
def dance():
for i in range(3):
print('dosomething2...%d' % i)
sleep(1)
print('dance end')
if __name__ == '__main__':
print('main thread startTime---:%s' % ctime())
t1 = threading.Thread(target=sign)
# t1 = threading.Thread(target=sign())
# 这里加了sign() 就不是分线程了 坑!
t2 = threading.Thread(target=dance)
t1.start()
t2.start()
#t1.join()
#t2.join() 这里加上Join之后会堵塞主线程
print('main thread endTime---:%s' % ctime())
日志:未加上Join
main thread startTime---:Fri Jan 26 16:56:11 2018
dosomething1...0
dosomething2...0
main thread endTime---:Fri Jan 26 16:56:11 2018
dosomething2...1
dosomething1...1
dosomething1...2
dosomething2...2
dance end
sign end
日志:加上Join
main thread startTime---:Fri Jan 26 16:59:53 2018
dosomething1...0
dosomething2...0
dosomething1...1
dosomething2...1
dosomething1...2
dosomething2...2
sign end
dance end
main thread endTime---:Fri Jan 26 16:59:56 2018
- threading 的一些方法
print(threading.current_thread()) # 输出当前线程
count = len(threading.enumerate()) # 输出当前线程总数
print('当前运行线程数:%d' % count)
自定义线程
需要继承threading.Thread,同时重写run方法
class MyThread(threading.Thread):
def run(self):
for i in range(3):
sleep(1)
message = 'I`m'+self.name +'@'+str(i)
print(message)
def main():
for i in range(3):
t = MyThread()
t.start()
if __name__ == '__main__':
main()
有兴趣学习的可以加群一起来探讨: 里面也有一些开发相关的PDF文档