本文主要採用threading庫
import threading
線程創建:
- 方法一:傳入參數實例化線程。
- 函數:threading.Thread(target, args)
- target:函數名
- args:傳入target函數的參數,用元組保存
- 函數:threading.Thread(target, args)
# encoding:utf-8
# coding:utf-8
import threading
def print_time(thread_name, delay):
print '線程{thread_name}啓動'.format(thread_name=thread_name)
count = 0
while count < 5:
print 'count:%d' % count
# 將線程阻塞delay秒
# time.sleep(delay)
count += 1
if __name__ == '__main__':
thread1 = threading.Thread(target=print_time, args=('thread1', 1))
thread2 = threading.Thread(target=print_time, args=('thread2', 2))
thread1.start()
thread2.start()
- 方法二:繼承thread.Thread類,重寫_init_()與_run_()方法
# coding:utf-8
import threading
class ThreadTest(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
print '線程{name}啓動'.format(name=self.name)
count = 0
while count < 5:
print 'count:%d' % count
count += 1
if __name__ == '__main__':
thread1 = ThreadTest('thread1')
thread2 = ThreadTest('thread2')
thread1.start()
thread2.start()
看到這裏的時候,剛接觸多線程的你(接觸過的可以省略這段)會發現運行的結果和我的不一致,不用緊張,多線程執行的過程並不是線性的,結果是不可預測的。強推以下文章,理解線程的執行過程:python 線程詳解–AstralWind
線程通信: