我沒有完全理解線程的概念我有一些問題。假設我們有下面的代碼:線程完成時檢查執行代碼
ExecCommand.java
// I don't know how this work, for now
package therads;
// Here we will have the methods and run them from the Main.java
public class ExecCommand implements Runnable
{
String name;
int time;
public ExecCommand(String s,int amount)
{
name = s;
time = amount;
}
// Run method (Runnable)
public void run()
{
try
{
// What to execute when the thread is started
System.out.printf("%s is sleeping for %d\n",name,time);
Thread.sleep(time);
System.out.printf("%s is done\n",name);
}
catch(Exception e)
{
}
}
// This dosen't work when the thread is stopped
public void stop()
{
try
{
System.out.printf("STOPPED!");
}
catch(Exception e)
{
}
}
// This dosen't work when the thread is started
public void start()
{
try
{
System.out.printf("Started!");
}
catch(Exception e)
{
}
}
}
,我叫他從:
Main.java
Thread t5 = new Thread(new ExecCommand("Good Function",1000));
t5.start();
我想到
println()
線程啓動時「開始」,完成時「停止」。有可能的?當線程完成時,它死了,完全從內存中釋放出來?如果沒有,我該怎麼做?
我該如何製作一個線程,每1000個毫秒重複一次,直到我按下一個鍵?我在想
while(true) { t5.start; }
,但我不知道。
我建議您在while循環中添加一個try {...} catch(InterruptedException e)(...},但這是它的jist。 – 2012-01-15 20:19:31
謝謝,我會試試:) – Master345 2012-01-15 20:21:28
它的工作原理完美地,我還添加了多少次重複線程 – Master345 2012-01-15 20:34:10