2016-09-26 79 views
0

我試圖停止一個Java線程,如果它運行6000毫秒。停止或中斷Java線程

以下代碼殺死線程R1無法停止線程。你能否請正確的代碼?

我試過用while(!Thread.currentThread()。isInterrupted())來停止線程。

import java.time.Duration; 
import java.time.Instant; 

class ThreadDemo extends Thread { 
    private Thread t; 
    private String threadName; 

    ThreadDemo(String name) { 
     threadName = name; 
     System.out.println("Creating " + threadName); 
    } 

    @Override 
    public void run() { 
     System.out.println("Running " + threadName); 
     try { 
      while (!Thread.currentThread().isInterrupted()) { 
       for (int i = 100; i > 0; i--) { 
        System.out.println("Thread: " + threadName + ", " + i); 
        // Let the thread sleep for a while. 
        Thread.sleep(600); 
       } 
      } 
     } catch (InterruptedException e) { 
      System.out.println("Thread " + threadName + " interrupted."); 
      Thread.currentThread().interrupt(); 

     } 
     System.out.println("Thread " + threadName + " exiting."); 
    } 

    @Override 
    public void start() { 
     System.out.println("Starting " + threadName); 
     if (t == null) { 
      t = new Thread(this, threadName); 
      t.start(); 
     } 
    } 
} 

public class Killthread { 

    public static void main(String args[]) throws InterruptedException { 
     Instant timeBefore = Instant.now(); 

     ThreadDemo R1 = new ThreadDemo("Thread-1"); 
     R1.start(); 
     System.out.println("Afte thread start"); 
     Thread.sleep(6001); 
     Instant timeAfter = Instant.now(); 
     if (Duration.between(timeBefore, timeAfter).toMillis() > 6000) { 
      R1.interrupt(); 
      // R1.stop(); 
      System.out.println("Thread Interrupted due to Time limitation."); 

     } 
    } 
} 
+1

該代碼看起來不錯,但我還沒有嘗試過。你看到了什麼結果? – markspace

+0

'start()'方法是怎麼回事?你能打印你的日誌並調用'super.start()'嗎?我不認爲需要嵌套的線程。 –

回答

3

你有兩個問題在你的代碼,首先你是不是睡你的主線程足夠長的時間,其次,你打斷了錯誤的線程。

6001毫秒不足以保證您的持續時間檢查是真實的。當我運行你的代碼時,主要的方法很少進入if塊。如果您更改爲睡眠時間爲6100毫秒,則應始終調用中斷。

你的第二個問題是你打斷了R1,但你需要打斷t

如果您在ThreadDemo中覆蓋interrupt()將呼叫傳遞給t,那麼它將接收中斷並中斷其執行線程。

例如

@Override public void interrupt() { 
    t.interrupt(); 
} 
1

問題是,你在ThreadDemo::start中啓動了一個完整的新的,不同的和不必要的線程。

@Override 
public void start() { 
    System.out.println("Starting " + threadName); 
    if (t == null) { 
     t = new Thread(this, threadName); 
     t.start(); 
    } 
} 

應該比較像

@Override 
public void start() { 
    System.out.println("Starting " + threadName); 
    super.start(); 
} 

而且在ThreadDemo擺脫private Thread t;的。

1

請從調用t.start()的重載啓動方法調用super.start(),它將調用線程類的start(),並負責創建新線程並將其註冊到線程調度程序。