python多线程详解(一)创建一个thread对象

注:所有操作均在3.9.5的python环境下进行

新建虚拟环境

利用conda新建一个python=3.9.5的虚拟环境

conda create -n py395 python=3.9.5

默认是没有安装jupyter notebook的。
开始菜单栏里找到Anaconda Navigator并打开,找到jupyter notebook选择安装。
在这里插入图片描述

打开该环境,并在该环境下打开jupyter notebook

conda activate py395
jupyter notebook

导入threading包

import threading
from threading import Thread
import time

创建一个函数,在线程里调用

def thread_proc(x):
    print(f"thread func start, argument is {x}.")
    time.sleep(2)
    print('thread func finished.')
  

创建一个线程对象:

'''
    有两种方法创建线程对象:
    一、传递一个函数作为参数
    二、继承threading类,重构run()方法,(只能重构 __init__ 和 run方法)
'''
# class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

# 方法一:
x = 10
my_thread = threading.Thread(target=thread_proc, args=(x,))
my_thread.start()

方法二:利用继承threading类的方式创建

'''
继承threading类创建线程对象,相当于重构run()方法。
并且只能重构 __init__ 方法和 run() 方法。
'''
class MyThread(threading.Thread):
    def __init__(self, name):
        super(MyThread, self).__init__()
        self.name = name
    
    def run(self):
        print(f"thread name is {self.name}.")

t1 = MyThread('test a')
t1.start()

下一节:介绍一个线程对象拥有的各种属性。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值