PYTHON添加线程

2018年10月4日07:21:30 发表评论 445 views

PYTHON添加线程

线程调用:

import threading #导入模块

#def main():
#    print(threading.active_count()) #获取已激活的线程数
#    print(threading.enumerate()) # 查看所有线程信息
#    print(threading.current_thread())#查看现在正在运行的线程,输出的结果是一个<_MainThread(...)>带多个<Thread(...)>

def thread_job():
    print('This is a thread of %s' % threading.current_thread())#添加线程,threading.Thread()接收参数target代表这个
    # 线程要完成的任务,需自行定义

def main():
    thread = threading.Thread(target=thread_job)
    thread.start()
if __name__ == '__main__':
    main()

运行结果:

E:\工作\开发类\python\anli\venv\Scripts\python.exe E:/工作/开发类/python/anli/多线程.py
This is a thread of <Thread(Thread-1, started 10764)>

Process finished with exit code 0

顺序执行和多线程执行:

import threading
import time

def run(n):
    print("task", n)
    time.sleep(1)
    print('2s')
    time.sleep(1)
    print('1s')
    time.sleep(1)
    print('0s')
    time.sleep(1)
run('t1')
run('t2')#串行执行
t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
t1.start()#多线程执行
t2.start()

运行结果:

E:\工作\开发类\python\anli\venv\Scripts\python.exe E:/工作/开发类/python/anli/多线程1.py
task t1
2s
1s
0s
task t2
2s
1s
0s
task t1
task t2
2s
2s
1s
1s
0s
0s

Process finished with exit code 0
多线程比顺序执行将近快了一倍,因为在t1等待过程中,由计时器参与工作,CPU切换到t2,等t2等待时间时又切回到t1。Andre
51changxue

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: