多任务可以由多进程完成,也可以由一个进程内的多线程完成。
import time
import threading
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep(1)
print('thread %s ended.' % threading.current_thread().name)
if __name__ == '__main__':
print('thread %s is running...' % threading.current_thread().name)
# t = threading.Thread(target=loop, name='LoopThread')
t = threading.Thread(target=loop)
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
thread MainThread is running...
thread Thread-1 is running...
thread Thread-1 >>> 1
thread Thread-1 >>> 2
thread Thread-1 >>> 3
thread Thread-1 >>> 4
thread Thread-1 >>> 5
thread Thread-1 ended.
thread MainThread ended.
Process finished with exit code 0
写上 join() 的话,爸爸就会等着儿子,否则爸爸就自己跑掉~(≧▽≦)/~啦啦啦