亲爱的所有我都有这种类型的代码:
public class Testimplements Runnable {
public static void main(String[] args) {
InTheLoop l= new InTheLoop();
Thread th = new Thread(l);
th.start();
th.interrupt();
}
@Override
public void run() {
int count = 0;
for (Integer i = 0; i <=10000000000000000000; i++) {
}
}
}
我知道有杀死线程的方法。例如:
// Example 1
if (Thread.interrupted()){
return;
}
// Example 2
if(flag){ // volatile
return;
}
但是如果没有if语句我就不能杀死线程吗?
答案 0 :(得分:2)
如果您真的需要,可以使用stop()
方法,但要注意它本质上是不安全的并且已弃用。
有关详细信息,请参阅http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html。
答案 1 :(得分:2)
据我所知,你必须自己为你的线程实现中断策略,它如何处理中断调用以及何时停止等等。
请参阅:http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html
答案 2 :(得分:1)
而不是线程更好地使用ExecutorService来更好地控制线程。
在oracle documentation中了解详情,此处为tutorial
答案 3 :(得分:0)
这个主题非常重要,我找不到任何明确的答案,所以我用OOP表格编写了一个示例代码来解释
import threading
import time
import tkinter as tk
class A(tk.Tk):
def __init__(self ,*args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.count = 0
self._running = True
self.Do = 0
A.Run(self)
def Thread_Terminate(self): # a method for killing the Thread
self._running =False
self.T.join()
self.Btn2.config (state='normal')
self.Btn1.config (state='disabled')
def Thread_Restart(self): # a thred for Start and Restart the thread
self.Btn1.config (state='normal')
self._running = True
self.T = threading.Thread(target=self.Core) # define Thread
if (self.T.is_alive() != True): # Cheak the Thread is that alive
self.T.start()
self.Btn2.config (state='disabled')
def Window (self):
self.title(" Graph ")
self.geometry("300x300+100+100")
self.resizable(width=False, height=False)
self.Lbl1 = Label(self,text = '0' ,font=('Times', -50, 'bold'), fg='Blue')
self.Lbl1.pack()
self.Lbl1.place(x=130, y=30 )
self.Btn1 = Button(self,text= 'Thread OFF',width=25,command = self.Thread_Terminate)
self.Btn1.pack()
self.Btn1.place(x=50,y=100)
self.Btn1 ['state'] = 'disable'
self.Btn2 = Button(self, text='Thread ON', width=25, command=self.Thread_Restart)
self.Btn2.pack()
self.Btn2.place(x=50, y=140)
self.Ent1 = Entry(self, width = 30, fg='Blue')
self.Ent1.pack()
self.Ent1.place(x=50, y=180)
def Core(self): # this method is the thread Method
self.count = 0
i = self.Ent1.get()
if (i==''):
i='10'
while (self._running and self.count<int(i)):
self.count +=1
self.Lbl1.config(text=str(self.count))
print(str (self.count)+'Thread Is ON')
time.sleep(0.5)
def Run(self):
A.Window(self)
self.mainloop()
if __name__ == "__main__":
Obj1 = A()