1.方法一 http://hi.baidu.com/javalang/item/72fabf2359a30b464799625e
也就是说当线程使用start方法运行起来后,只有当run方法运行结束,一个线程才会结束。
import threading
from threading import Thread
import time
class MyThread(Thread):
over=False
def __init__(self):
Thread.__init__(self) def run(self):
while not self.over:
print "hello"
time.sleep(2)
def kill(self):
self.over=Trueif __name__=='__main__':
t=MyThread()
t.start()
print 'wait 5s'
time.sleep(5)
t.kill()
该方法适合run()方法中不包含死循环程序,若run()包含死循环,则此方法无法结束该线程
2.方法二
import threading
import thread
import time
import os
import urllibdef timer():
time_start = time.time()
while(1):
time_end = time.time()
if ((time_end - time_start) > 4):
return 1def printf():
i = 0
while(1):
i = i + 1
print i
time.sleep(1)def run():
sub_thread1 = thread.start_new_thread(printf,())
try:
if(timer()):
sub_thread1.exit()
except AttributeError:
pass
print "stop\n"
print "success\n"if __name__=='__main__':
run()
开一个线程,该线程为死循环,则使用Thread类的exit方法可以退出,一般情况建议使用Thread.threading
若子线程触发了一个新的进程,则此方法无效,需使用父进程杀死该子进程
方法三:
import threading
import thread
import time
import os
import urllibdef timer():
time_start = time.time()
while(1):
time_end = time.time()
if ((time_end - time_start) > 10):
return 1def printf():
i = 0
while(1):
i = i + 1
print i
time.sleep(1)
#if(i > 15):
# breakdef run(filename):
sub_thread = thread.start_new_thread(os.system,('java -jar'+' '+ filename,))
try:
if(timer()):
sub_thread.exit()
except AttributeError:
pass
tasks = os.popen('jps -m').readlines()
#print tasks
found_task = ""
PID_end_position = 0
for task in tasks:
if filename[3:] in task:
found_task = task
PID_end_position = found_task.find(filename[3:]) - 1
break
if found_task:
PID = found_task[0 : PID_end_position]
os.system("taskkill /f /PID " + PID)
time.sleep(3)
os.system('del /f'+' '+filename)if __name__=='__main__':
run('D:\\ba-finance-tuangou-bp-job-1.0.1-SNAPSHOT.jar')