python自学之多线程编程

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)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值