-
threading
启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:
import time, 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) print('thread %s is running...' % threading.current_thread().name) t = threading.Thread(target=loop, name='LoopThread') t.start() t.join() print('thread %s ended.' % threading.current_thread().name)
用threading模块中的current_thread()函数返回当前线程的实例。
主线程实例的名字叫做MainThread。
子线程的名字在创建时指定。不指定自动命名为Thread-1,Thread-2……执行结果如下:
thread MainThread is running... thread LoopThread is running... thread LoopThread >>> 1 thread LoopThre
python之多线程
最新推荐文章于 2024-03-03 21:50:34 发布