发布网友 发布时间:2022-04-25 12:47
共1个回答
热心网友 时间:2022-04-18 06:15
可以新建一个线程作为父线程,然后实际工作是在它的一个子线程里面做,父线程循环检测一个变量来决定是否退出。Talk
is
cheap
import
threading
class
TestThread(threading.Thread):
def
__init__(self,
thread_num=0,
timeout=1.0):
super(TestThread,
self).__init__()
self.thread_num
=
thread_num
self.stopped
=
False
self.timeout
=
timeout
def
run(self):
def
target_func():
inp
=
raw_input("Thread
%d:
"
%
self.thread_num)
print('Thread
%s
input
%s'
%
(self.thread_num,
inp))
subthread
=
threading.Thread(target=target_func,
args=())
subthread.setDaemon(True)
subthread.start()
while
not
self.stopped:
subthread.join(self.timeout)
print('Thread
stopped')
def
stop(self):
self.stopped
=
True
def
isStopped(self):
return
self.stopped
thread
=
TestThread()
thread.start()
import
time
print('Main
thread
Wainting')
time.sleep(2)
thread.stop()
thread.join()