簡體   English   中英

如何避免檢查 JAVA 中到處中斷的線程

[英]how to avoid checking thread interrupted everywhere in JAVA

我有兩個算法 A,B 用於計算 NP 難題的解決方案,這可能需要很多時間。 然后在主線程 MI 中分別為算法 A 和算法 B 創建線程 A 和線程 B。 當線程A或線程B中的任何一個完成計算或兩者都達到超時時,M在那些未完成的線程上調用中斷。 M 對 5,000 多個測試用例重復此過程。

由於算法A和B沒有任何可中斷的操作,中斷不會導致中斷異常,因此這些未完成的線程將繼續在后台運行,最終耗盡堆memory,因為未完成的線程越來越多。

然后我需要在兩種算法中手動檢查線程的isInterrupted 但我不想到處檢查它們的效率和代碼可讀性問題。

例如,原始算法是

public class AlgA {
  public void run() {
    do1();
    do2();
    ...
    do100();
  }
}

我不想

public class AlgA {
  public void run() throws InterruptedException {
    do1();
    check();
    do2();
    check();
    ...
    check();
    do100();
  }
  private void check() throws InterruptedException {
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
  }
}

一種方法可能是將中斷檢查和方法調用包裝在一些 util mehtod 中:

public class AlgA {
  protected static void checkAndCall(Runnable action) 
      throws InterrruptedException {
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
    action.run()
  }

  public void run() {
    checkAndCall(this::do1);
    checkAndCall(this::do2);
    ...
    checkAndCall(this::do100);
  }
}

你可以保持簡單如下:

public class Test {
    public static void main(String args[]) {
        Thread threadA=new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        while(true) {
                            if (Thread.interrupted()) {
                                break;
                            }
                            //Continue the execution
                        }
                    }
                }
        );

        threadA.start();

        Thread threadB=new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        while(true) {
                            if (Thread.interrupted()) {
                                break;
                            }
                            //Continue the execution
                        }
                    }
                }
        );

        threadB.start();

        // Assigning someConditionMeets=true just for illustration.
        // In actual code someConditionMeets will store the result of some logic/function
        boolean someConditionMeets=true;
        if(someConditionMeets) {
            threadA.interrupt();
            threadB.interrupt();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM