Python——线程1

多线程并发

from threading import Thread
import time
#多线程并发
def func(n):
    time.sleep(1)
    print(n)
    
for i in range(10):
    Thread(target=func,args=(1,))
    t.start()
View Code

面向对象的方法开启多线程

class MyTread(Thread):
    def __init__(self,arg):
        super().init()
        self.arg = arg
    def run(self):
        time.sleep(1)
        print(self.arg)
        
t = MyTread(10)
t.start
View Code

 线程池

import time
from concurrent.futures import ThreadPoolExecutor
def func(n):
    time.sleep(2)
    print(n)
    return n*n

def call_back(m):
    print('结果是 %s'%m.result())

tpool = ThreadPoolExecutor(max_workers=5)   #  默认 不要超过cpu个数*5
for i in  range(20):
    tpool.submit(func,i).add_done_callback(call_back)


# tpool.map(func,range(20))  # 拿不到返回值
# t_lst = []
# for i in  range(20):
#     t = tpool.submit(func,i)
#     t_lst.append(t)
# tpool.shutdown()  # close+join    #
# print('主线程')
# for t in t_lst:print('***',t.result())
View Code

 

posted @ 2018-10-30 08:38  澄心元素  阅读(102)  评论(0编辑  收藏  举报