4 回答

TA貢獻1836條經驗 獲得超5個贊
如果你暴露線程執行程序讓你運行,那么你可以打斷它。對我來說,這只打印1
4次表明中斷成功。
請記住,這依賴于一個事實,即Thread.sleep
和System.out.println
是中斷的。如果你沒有檢查Thread.isInterrupted
(就像他們兩個那樣),你仍然可能無法中斷線程。
ExecutorService executor = Executors.newSingleThreadExecutor();private void test() throws InterruptedException { AtomicReference<Thread> thread = new AtomicReference<>(); Future<Object> task = executor.submit(() -> { // Keep track of the thread. thread.set(Thread.currentThread()); try { while (true) { Thread.sleep(1000); System.out.println("1"); } } finally { System.out.println("Interrupted: " + Thread.currentThread().isInterrupted()); } }); Thread.sleep(5000); // Interrupt the thread. thread.get().interrupt(); Thread.sleep(5000); System.out.println("Press <Enter> to shutdown"); new Scanner(System.in).nextLine(); executor.shutdown(); System.out.println("Press <Enter> to shutdown NOW"); new Scanner(System.in).nextLine(); executor.shutdownNow();}

TA貢獻1876條經驗 獲得超7個贊
Threre在某些方面
為循環條件添加附加條件,
boolean shouldContinue
因此將此設置為false將在某個時刻退出循環如果您可以編寫自己的功能(您擁有應用程序),您可以編寫代碼來列出所有線程并強制給定線程停止使用
Thread#stop
(不安全)或Thread#interrupt
(更安全)。如果您不擁有該應用程序 - 就像您正在運行一些應用程序 - 您可以使用自定義運行它,
javaagent
這將允許您執行與第2點相同的操作。
2和3,與prober集成,例如套接字,可以允許您在已經運行的進程中從外部執行此操作,例如。來自CLI

TA貢獻1824條經驗 獲得超8個贊
請閱讀shutdownNow()方法的javadoc?。它非常清楚地說:
除盡力嘗試停止處理主動執行任務之外,沒有任何保證。例如,典型的實現將通過Thread.interrupt()取消,因此任何未能響應中斷的任務都可能永遠不會終止。
因此,您需要做的是在代碼中更改提交的任務以響應Thread.interrupt()
方法。即你需要更改你的行while (true)
以while (true && !Thread.currentTrhead().isInterrupted())
獲取更多細節,在特定方法中讀取線程類的?javadoc?interrupt()
,interrupted()
以及isInterrupted()
添加回答
舉報