多线程【thread】创建【1】

随便写写:)

【参考】:Python内置库:threading(多线程) - 山上下了雪-bky - 博客园 (cnblogs.com)

(1)多线程实现:

python旧版本thread 新版本(2-7 3 )之后的引进了threading,且thread改为_thread

ps:多线程是指打开一个线程,运行多个线程! 【个人理解:比如打开了一个cpu,在这个cpu中跑了两个任务:

任务一:函数一(参数一)

任务二:函数一(参数二)

pps:

  • threading.active_count():返回当前存活的threading.Thread线程对象数量,等同于len(threading.enumerate())。
  • threading.current_thread():返回此函数的调用者控制的threading.Thread线程对象。如果当前调用者控制的线程不是通过threading.Thread创建的,则返回一个功能受限的虚拟线程对象。
  • threading.get_ident():返回当前线程的线程标识符。注意当一个线程退出时,它的线程标识符可能会被之后新创建的线程复用。
  • threading.enumerate():返回当前存活的threading.Thread线程对象列表。
  • threading.main_thread():返回主线程对象,通常情况下,就是程序启动时Python解释器创建的threading._MainThread线程对象。
  • threading.stack_size([size]):返回创建线程时使用的堆栈大小。也可以使用可选参数size指定之后创建线程时的堆栈大小,size可以是0或者一个不小于32KiB的正整数。如果参数没有指定,则默认为0。如果系统或者其他原因不支持改变堆栈大小,则会报RuntimeError错误;如果指定的堆栈大小不合法,则会报ValueError,但并不会修改这个堆栈的大小。32KiB是保证能解释器运行的最小堆栈大小,当然这个值会因为系统或者其他原因有限制,比如它要求的值是大于32KiB的某个值,只需根据要求修改即可。

(2)扣得~

threading.Thread创建线程简单示例:

def test_thread(para='hi', sleep=3):
    """线程运行函数"""
    time.sleep(sleep)
    print(para)
def main():
    # 创建线程
    thread_hi = threading.Thread(target=test_thread)
    thread_hello = threading.Thread(target=test_thread, args=('hello', 1))
    # 启动线程
    thread_hi.start()
    thread_hello.start()
    print('Main thread has ended!')
if __name__ == '__main__':
    main()

简单来说:不同的参数用了一样的函数调用,且二者同时运行! 

"""
通过继承threading.Thread的子类创建线程
"""
import time
import threading


class TestThread(threading.Thread):
    def __init__(self, para='hi', sleep=3):
        # 重写threading.Thread的__init__方法时,确保在所有操作之前先调用threading.Thread.__init__方法
        super().__init__()
        self.para = para
        self.sleep = sleep

    def run(self):
        """线程内容"""
        time.sleep(self.sleep)
        print(self.para)


def main():
    # 创建线程
    thread_hi = TestThread()
    thread_hello = TestThread('hello', 1)
    # 启动线程
    thread_hi.start()
    thread_hello.start()
    print('Main thread has ended!')


if __name__ == '__main__':
    main()

"""
使用join方法阻塞主线程
"""
import time
import threading


def test_thread(para='hi', sleep=5):
    """线程运行函数"""
    time.sleep(sleep)
    print(para)


def main():
    # 创建线程
    thread_hi = threading.Thread(target=test_thread)
    thread_hello = threading.Thread(target=test_thread, args=('hello', 1))
    # 启动线程
    thread_hi.start()
    thread_hello.start()
    time.sleep(2)


    print('马上执行join方法了')
    # 执行join方法会阻塞调用线程(主线程),直到调用join方法的线程(thread_hi)结束
    thread_hi.join()


    print('线程thread_hi已结束')
    # 这里不会阻塞主线程,因为运行到这里的时候,线程thread_hello已经运行结束了
    thread_hello.join()
    print('Main thread has ended!')

    # 以上代码只是为了展示join方法的效果
    # 如果想要等所有线程都运行完成后再做其他操作,可以使用for循环
    # for thd in (thread_hi, thread_hello):
    #     thd.join()
    #
    # print('所有线程执行结束后的其他操作')


if __name__ == '__main__':
    main()

 

join:阻塞自身的线程------可以先run别的线程,自身线程等待!

import threading
import time

def test():

    for i in range(5):
        print(threading.current_thread().name+' test ',i)
        time.sleep(0.5)


thread = threading.Thread(target=test,name='TestThread')
thread.start()
thread.join()

for i in range(5):
    print(threading.current_thread().name+' main ', i)
    print(thread.name+' is alive ', thread.isAlive())
    time.sleep(1)

TestThread test  0
TestThread test  1
TestThread test  2
TestThread test  3
TestThread test  4
MainThread main  0
TestThread is alive  False
MainThread main  1
TestThread is alive  False
MainThread main  2
TestThread is alive  False
MainThread main  3
TestThread is alive  False
MainThread main  4
TestThread is alive  False 

默认的情况是,join() 会一直等待对应线程的结束,但可以通过参数赋值,等待规定的时间就好了。

def join(self, timeout=None):

timeout 是一个浮点参数,单位是秒。

如果我们更改上面的代码。

thread.join(1.0)

TestThread test  0
TestThread test  1
MainThread main  0
TestThread is alive  True
TestThread test  2
TestThread test  3
MainThread main  1
TestThread is alive  True
TestThread test  4
MainThread main  2
TestThread is alive  False
MainThread main  3
TestThread is alive  False
MainThread main  4
TestThread is alive  False 

主线程只等待了 1 秒钟。



参考:https://blog.csdn.net/briblue/article/details/85101144 

Thread 的名字

每一个 Thread 都有一个 name 的属性,代表的就是线程的名字,这个可以在构造方法中赋值。

import threading
import time

def test():

    for i in range(5):
        print(threading.current_thread().name+' test ',i)
        time.sleep(1)


thread = threading.Thread(target=test)
thread.start()

for i in range(5):
    print(threading.current_thread().name+' main ', i)
    time.sleep(1)
result:

Thread-1 test  0
MainThread main  0
Thread-1 test  1
MainThread main  1
Thread-1 test  2
MainThread main  2
Thread-1 test  3
MainThread main  3
Thread-1 test  4
MainThread main  4

 thread = threading.Thread(target=test,name='TestThread')  定义线程名字

 

Thread 的生命周期
调用 start() 方法后,thread 会开始运行。
thread 代码正常运行结束或者是遇到异常,线程会终止。
可以通过 Thread 的 is_alive() 方法查询线程是否还在运行。

值得注意的是,is_alive() 返回 True 的情况是 Thread 对象被正常初始化,start() 方法被调用,然后线程的代码还在正常运行。
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值