[英]Thread time of execution in java
我在其中調用方法的java中有一個線程。我為每個線程存儲一個映射,以便可以殺死它。 我的示例代碼是:
Thread thread = new Thread( new Runnable() {
public void run() {
executeMethod();
}
} );
thread.start();
thread.setName("some Name");
//Create Map to save each method call as thread
threadMap.put( "some Name", thread );
現在,我想通過殺死線程來停止方法調用,所以我有類似以下內容:
public static void stop( String threadName ) {
if ( StringUtils.isNotEmpty( threadName ) ) {
Thread t = threadMap.get( threadName );
if ( t != null && t.isAlive() ) {
System.out.println( "Going to kill the thread:" + threadName );
t.interrupt();
System.out.println( "killed!!" );
} else {
System.out.println( "THREAD is null" );
}
}
}
問題是當我調用我的stop方法時,t.isAlive()為false。 我認為方法的執行時間將是線程的存活時間。我是對的還是我誤解了?
線程在run()
方法返回后也會死掉。 在這種情況下,線程將不活動。 將sleep
語句添加到run()
方法中,並在其之前和之后添加print語句,以確保線程的當前狀態。
Thread.interrupt不會殺死線程,只是在線程暫停時恢復它,通常,手動殺死線程不是一個好主意。 閱讀此問題以了解為什么以及要怎么做。
As per Thread Class java doc
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
Thread.getState() will return you state of the thread
which you can check if thread is still running and then can kill it.
Thread.State = getState() Returns the state of this thread.
A thread state. A thread can be in one of the following states:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
該方法的執行時間和線程的活動時間將不同。 以下是線程生命周期的內容:
調用start()方法后,線程處於可運行狀態,但是線程調度程序未將其選擇為正在運行的線程。
因此, start()
方法的調用不一定保證線程的執行。 這取決於jvm和Opetating System如何處理線程。 在啟動executeMethod
方法之前,線程可能會保持runnable
狀態一段時間,或者在調用start()
可能立即啟動executeMethod
,但是不能保證這兩種行為都可以保證。 這是javadoc所說的:
每個線程都有一個優先級。 具有較高優先級的線程優先於具有較低優先級的線程執行。 每個線程可能會也可能不會被標記為守護程序。 當在某個線程中運行的代碼創建新的Thread對象時,新線程的優先級最初設置為與創建線程的優先級相等,並且當且僅當創建線程是守護程序時,該線程才是守護程序線程。
因此,您不應期望線程的活動時間就是方法的執行時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.