from threading import Thread
import threading
import random
import time
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
self.count = 0
def run(self):
time.sleep(1)
this_name = threading.current_thread().getName()
print("%s has begin to eat" % this_name)
while True:
self.count += 1
print("%s has eaten %s hambergurs" % (this_name, self.count))
time.sleep(random.random()*4)
th1 = MyThread()
th2 = MyThread()
th1.start()
th2.start()
del th1
print("th1 is deleted")
print(th1)代码的输出如下:
th1被删除
回溯(最近一次调用):
文件"D:/Data/data_file/pycharm_project/test/test.py",第33行,在
打印(Th1)
NameError:名称“th1”未定义为
线程-1已经开始吃-线程-2已经开始吃
螺纹-2已经吃了1只黄腿猴。
线-1已经吃了一只老鼠。
线-2已经吃了两个哈伯鱼。
线-1已经吃了2只老鼠。
螺纹-1已经吃了3只老鼠。
螺纹-2已经吃了3只狐猴。
所以在下面的代码之后
del th1th1被删除
但是Thread-1仍然在运行。
del th1为什么上面的代码没有杀死Thread-1
发布于 2022-03-02 09:30:46
如果坚持使用del命令,可以使用以下代码:
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
self.count = 0
self.__kill = False
def run(self):
time.sleep(1)
this_name = self.name
print("%s has begin to eat" % this_name)
while not self.__kill:
self.count += 1
print("%s has eaten %s hambergurs" % (this_name, self.count))
time.sleep(random.random()*4)
def kill(self):
self.__kill = True
def __del__(self):
self.__kill = True现在您可以使用th1.kill()和del th1了
p.s .使用self.name代替threading.current_thread().getName()
https://stackoverflow.com/questions/71319609
复制相似问题