python中线程thread的使用

创建一个通用线程类MyThread,继承自threading中的Thread

创建类,将需要执行的函数作为参数传入,函数参数也作为参数传入

class MyThread(threading.Thread):
    def __init__(self, name, thread_id, exec_func, **kwargs):
        threading.Thread.__init__(self)
        self.name = name
        self.thread_id = thread_id
        self.function = exec_func
        self.args = {}
        for k, v in kwargs.items():
            self.args[k] = v

    def print_extern_args(self):
        print(self.args)

重写run方法,当调用run方法时,自动执行函数

    def run(self):
        print('Starting ' + self.name + ' thread')
        self.function(self.args['sleep_time'])
        print('Exiting ' + self.name + ' thread')

测试代码

先定义两个函数,参数都是休眠时间

def thread_test1(sleep_time: int):
    for i in range(1000000000):
        # 获取当前日期时间
        now = datetime.now()
        print(f"{__name__},wait time is {sleep_time}")
        time.sleep(sleep_time)
        print(f"当前系统日期和时间是:{now.strftime("%Y-%m-%d %H:%M:%S")}")
        print(f"{__name__},wait time is {sleep_time+1}")
        time.sleep(sleep_time+1)
        print(f"如何避免焦虑")


def thread_test2(sleep_time: int):
    for i in range(1000000000):
        # 获取当前日期时间
        now = datetime.now()
        print(f"{__name__},wait time is {sleep_time}")
        time.sleep(sleep_time)
        print(f"TMD,这操蛋的世界,当前系统日期和时间是::{now.strftime("%Y:%m:%d %H-%M-%S")}")
        print(f"{__name__},wait time is {sleep_time+1}")
        time.sleep(sleep_time+1)
        print(f"唯有奋斗!")

实例化MyThreas,将函数及参数作为类参数传入

my_thread1 = MyThread(name='thread_test1', thread_id=1, exec_func=thread_test1, sleep_time=5)
my_thread1.print_extern_args()
my_thread2 = MyThread(name='thread_test2', thread_id=2, exec_func=thread_test2, sleep_time=5)
my_thread2.print_extern_args()
my_thread1.start()
my_thread2.start()

最后的参数sleep_time=5是函数的参数。

threading中join函数的作用

源代码函数的解释

"""
Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is
called terminates -- either normally or through an unhandled exception
or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a
floating-point number specifying a timeout for the operation in seconds
(or fractions thereof). As join() always returns None, you must call
is_alive() after join() to decide whether a timeout happened -- if the
thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will
block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current
thread as that would cause a deadlock. It is also an error to join() a
thread before it has been started and attempts to do so raises the same
exception.

"""

解释就是,调用join的线程会一直阻塞主线程__main__,直到调用join的线程执行结束或者超时结束或者因为异常退出。

测试代码

my_thread1 = MyThread(name='thread_test1', thread_id=1, exec_func=thread_test1, sleep_time=5)
my_thread1.print_extern_args()
my_thread2 = MyThread(name='thread_test2', thread_id=2, exec_func=thread_test2, sleep_time=5)
my_thread2.print_extern_args()
my_thread1.start()
my_thread2.start()

my_thread1.join()
my_thread2.join()
# 只有当my_thread1,my_thread2执行结束,下面的代码才会被执行
print('start execute next thread......')
my_org_thread1 = threading.Thread(target=thread_test1, args=(1,))
my_org_thread2 = threading.Thread(target=thread_test2, args=(1,))
my_org_thread1.start()
my_org_thread2.start()

执行结果如下:
{‘sleep_time’: 5}
{‘sleep_time’: 5}
Starting thread_test1 thread
main,wait time is 5
Starting thread_test2 thread
main,wait time is 5
TMD,这操蛋的世界,当前系统日期和时间是::2024:10:04 01-07-11当前系统日期和时间是:2024-10-04 01:07:11
main,wait time is 6

main,wait time is 6
如何避免焦虑唯有奋斗!
main,wait time is 5

main,wait time is 5
当前系统日期和时间是:2024-10-04 01:07:22TMD,这操蛋的世界,当前系统日期和时间是::2024:10:04 01-07-22
main,wait time is 6

main,wait time is 6
唯有奋斗!如何避免焦虑
main,wait time is 5

main,wait time is 5
TMD,这操蛋的世界,当前系统日期和时间是::2024:10:04 01-07-33当前系统日期和时间是:2024-10-04 01:07:33
main,wait time is 6

main,wait time is 6
唯有奋斗!如何避免焦虑
main,wait time is 5

main,wait time is 5
TMD,这操蛋的世界,当前系统日期和时间是::2024:10:04 01-07-44
main,wait time is 6当前系统日期和时间是:2024-10-04 01:07:44
main,wait time is 6

如何避免焦虑唯有奋斗!
main,wait time is 5

main,wait time is 5
当前系统日期和时间是:2024-10-04 01:07:55TMD,这操蛋的世界,当前系统日期和时间是::2024:10:04 01-07-55

main,wait time is 6
main,wait time is 6
如何避免焦虑
main,wait time is 5
唯有奋斗!
main,wait time is 5
当前系统日期和时间是:2024-10-04 01:08:06
main,wait time is 6
TMD,这操蛋的世界,当前系统日期和时间是::2024:10:04 01-08-06
main,wait time is 6
如何避免焦虑
main,wait time is 5
唯有奋斗!
main,wait time is 5
当前系统日期和时间是:2024-10-04 01:08:17
main,wait time is 6
TMD,这操蛋的世界,当前系统日期和时间是::2024:10:04 01-08-17
main,wait time is 6
如何避免焦虑唯有奋斗!
main,wait time is 5

测试结果

可以看到my_thread1和my_thread2之后的print一直未得到执行,后面创建的两个线程my_org_thread1,my_org_thread2也一直未得到执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值