Thread
類的stop()
方法終止執行緒執行。當執行緒停止,它就不能通過start()
方法重新啟動。
語法
public final void stop()
public final void stop(Throwable obj)
引數
obj
:要丟擲的Throwable
物件。異常
SecurityException
:如果當前執行緒無法修改執行緒,則丟擲此異常。範例
public class JavaStopExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaStopExp t1=new JavaStopExp ();
JavaStopExp t2=new JavaStopExp ();
JavaStopExp t3=new JavaStopExp ();
// call run() method
t1.start();
t2.start();
// stop t3 thread
t3.stop();
System.out.println("Thread t3 is stopped");
}
}
執行上面範例程式碼,得到以下結果:
Thread t3 is stopped
Thread-0
1
Thread-1
1
Thread-0
2
Thread-1
2
Thread-1
3
Thread-0
3
Thread-1
Thread-0
4
4