注:所有操作均在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()
下一节:介绍一个线程对象拥有的各种属性。