2015-09-08 91 views
1

我有方法的類(其中運行的線程):中斷線程

public void execute() { 
    List<Task> task = read(); 
    for (Task task: tasks) { 
     Thread thread = new Thread(task); 
     thread.start(); 
     try { 
      thread.join(); 
     } catch (InterruptedException e) { 
      break; 
     } 
    } 
} 

而且我有方法的一些任務類是這樣的:

public void run() { 
    Thread.currentThread.interrupt(); 
} 

如何設置中斷從任務類的主要類?

+0

傳遞給主線程的引用到任務線程,那麼只需要調用'了Thread.interrupt()'上的參考。 –

+0

@AndyTurner這不是個好主意,任務是在另一個地方創建的。你知道另一個解決方案嗎? – nelinuj

+0

建議您查看http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html和關聯的類。通過使用這些新類來處理這種基本問題,可以避免許多問題。 –

回答

0

我希望我能理解你的情況,這可能會有所幫助。嘗試一下。

try { 
     thread.join(); 
     if(thread.isInterupted()){break;/*?!*/} 
    } catch (InterruptedException e) { 
     break; 
    } 


或者

/*public static */volatile boolean work=true; 
public void execute() { 
    List<Task> task = read(); 
    for (Task task: tasks) { 
     if(!work){break;} 
     Thread thread = new Thread(task); 
     thread.start(); 
     try { 
      thread.join(); 
     } catch (InterruptedException e) { 
      break; 
     } 
    } 
} 
... 
public void run() { 
    Thread.currentThread.interrupt(); 
    work=false; 
}