runable方式启动线程:
#!/usr/bin/env python
# encoding: utf-8
'''
@author: heshengjin-何胜金
@contact: 2356899074@qq.com
@software: pycharm
@file: threadingTest.py
@time: 2018/12/20 12:08
@desc:多线程编程-开启线程的两种方式-和java一样继承和runable方式
'''
import threading
import time
# <type 'int'>
# <type 'tuple'>
a = (6)
b = (6,)
print( type(a))
print( type(b))
# ==============================方式1:runable方式===============================
def loop(x):
print("******%s start******" % threading.current_thread().name)
for i in range(x):
time.sleep(1)
print("%s:%d" % (threading.current_thread().name, i))
print("******%s stop******" % threading.current_thread().name)
print("----%s start----" % threading.current_thread().name)
# threading.Thread参数是tuple,只要一个len()==1
t1 = threading.Thread(target=loop, args=(6,))
# t1.setDaemon(True) 主线程结束就结束所有
t1.setDaemon(True)
t1.start()
# t1.join()所有子线程结束才结束主线程
t1.join()
print("----%s stop-----" % threading.current_thread().name)
继承Thread方式启动线程:
#!/usr/bin/env python
# encoding: utf-8
'''
@author: heshengjin-何胜金
@contact: 2356899074@qq.com
@software: pycharm
@file: threadingTest.py
@time: 2018/12/20 12:08
@desc:多线程编程-开启线程的两种方式-和java有点类似继承和runable方式
'''
import threading
from threading import Thread
import time
# <type 'int'>
# <type 'tuple'>
a = (6)
b = (6,)
print( type(a))
print( type(b))
# ==============================方式2:继承方式===============================
class Sayhi(Thread):
def __init__(self, name):
super(Sayhi,self).__init__()
self.name = name
def run(self):
time.sleep(2)
print(r'%s say hello' % (self.name))
print(threading.current_thread().name)
if __name__ == '__main__':
t = Sayhi('mike')
t.start()
# t.join()所有子线程结束才结束主线程
t.join()
print("主线程")
print(threading.current_thread().name)
锁:
#!/usr/bin/env python
# encoding: utf-8
'''
@author: heshengjin-何胜金
@contact: 2356899074@qq.com
@software: pycharm
@file: threadingTestLock.py
@time: 2018/12/20 13:36
@desc:并发编程-多线程
+=(原子操作)
'''
import threading
deposit = 0 # 银行存款-主线程中-子线程共享主线程
lock_deposit = threading.Lock()
def change_it(n):
# 使用外层的变量,自己不去定义变量
global deposit
deposit += n # 存
deposit -= n # 取
# deposit = deposit + n # 存
# deposit = deposit - n # 取
def loop(n):
for i in range(100000):
lock_deposit.acquire() # 先获取锁
try:
change_it(n)
finally:
lock_deposit.release() # 确保释放锁
t1 = threading.Thread(target=loop, args=(5,))
t2 = threading.Thread(target=loop, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(deposit)
一般线程池:
#!/usr/bin/env python
# encoding: utf-8
'''
@author: heshengjin-何胜金
@contact: 2356899074@qq.com
@software: pycharm
@file: threadingPoolTest.py
@time: 2018/12/20 15:08
@desc:线程池
'''
import time
import threadpool
def sayhello(str='默认值'):
print(str)
time.sleep(2)
name_list =['xiaozi','aa','bb','cc']
start_time = time.time()
pool = threadpool.ThreadPool(10)
requests = threadpool.makeRequests(sayhello, name_list)
[pool.putRequest(req) for req in requests]
pool.wait()
print( '%d second'% (time.time()-start_time))
类似java方式的强悍future线程:
from concurrent import futures
##1、主线程中可以获取某一个线程的状态或者某一任务的状态以及返回值
##2、当一个线程完成的时候主线程能立即知道
##3、futures可以让多线程和多进程编码接口一致
import time
def get_html(times):
time.sleep(times)
print("get page {} success".format(times))
return times
executor=futures.ThreadPoolExecutor(max_workers=2)
##submit将任务函数放到线程池中,会立即执行非阻塞
task1=executor.submit(get_html,(3))
task2=executor.submit(get_html,(2))
print(task1.done())##立即执行done()是False
print(task2.done())##立即执行done()是False
print(task1.result())##result是阻塞的获取线程结果3
print(task2.result())##2
print(task1.done())##由于result阻塞导致任务完成了 True
print(task2.done())##任务完成了True
# print("")
##要获取已完成的task的返回
# times_list=[3,4,1,2,3,1]
# tasks=[ executor.submit(get_html,(a)) for a in times_list]
# for future in futures.as_completed(tasks):
# result=future.result()
# print("%ss task done"%result)
# print("")
# for result in executor.map(get_html,times_list):##此两句相当于上面四行代码
# print("%s s task done"%result)