Python的多线程

线程间的关系

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import threading
import time

def MyThread(n):
    print("Running Thread",n)
    print(threading.current_thread()) #打印当前线程的类型
    time.sleep(2)

for i in range(20):
    t = threading.Thread(target=MyThread,args=(i,))
    t.start()

print("Running Main Threading",threading.current_thread())
print(threading.active_count()) #计算线程数

 运行结果

主线程和子线程同时执行,然后脚本执行Mythread函数里的time.sleep(2),运行停顿大概2秒

线程数为当前主线程和子线程数之和

 

def MyThread(n):
    print("Running Thread",n)
    print(threading.current_thread())
    time.sleep(2)

for i in range(20):
    t = threading.Thread(target=MyThread,args=(i,))
    t.start()

 这段代码为主线程启动的子线程

 

print("Running Main Threading",threading.current_thread())
print(threading.active_count())

 这段代码为主线程执行的线程

多线程的等待

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import threading
import time

All_Thread = []

def MyThread(n):
    print("Running %s Thread"%n)
    time.sleep(2)

for i in range(20):
    t = threading.Thread(target=MyThread,args=(i,))
    t.start()

print("Finished All Sub-thread")

 运行,查看结果

该脚本同时执行主线程和子线程

如果想先执行完子线程再执行主线程,可以使用join()

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import threading
import time

All_Thread = []

def MyThread(n):
    print("Running %s Thread"%n)
    time.sleep(2)

for i in range(20):
    t = threading.Thread(target=MyThread,args=(i,))
    t.start()
    All_Thread.append(t)

for t in All_Thread:
    t.join()

print("Finished All Sub-thread")

 运行,查看结果

先执行了子线程,然后停留了大概2秒,再执行了主线程

线程号

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import threading

def MyThread():
    print(threading.get_ident())

for i in range(10):
    t = threading.Thread(target=MyThread)
    t.start()

 运行结果

打印出了这10个子线程的id号

posted @ 2017-12-12 23:01  Sch01aR#  阅读(262)  评论(0编辑  收藏  举报