簡體   English   中英

java - 暫停所有正在運行的線程一段時間

[英]java - Pausing all running threads for some time

例如考慮以下場景。

App1:我有一個多線程的java應用程序,它在DB中輸入了很多文件。

App2:當我使用其他應用程序訪問數據庫時,獲取結果的速度很慢。

因此,當兩個應用程序同時工作時,DB 在前端應用程序 2 上獲取結果會花費大量時間。

在這里,我想暫停 App1 上的所有事務(線程)一些“x 分鍾”時間。 考慮到在使用應用程序 2 時已經安裝了觸發器。 所以當 App2 空閑時,App1 會像什么都沒發生一樣恢復。 請列出實現此目的的一些或一種最佳方法

Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) {
        entry.getKey().sleep();
    }

這並不奏效。

只是為了嘗試:

private List<PausableThread> threads = new ArrayList<PausableThread>();

private void pauseAllThreads()
{
    for(PausableThread thread : this.threads)
    {
        thread.pause();
    }
}

你的 Thread 類將是這樣的:

public class MyThread extends Thread implements PausableThread
{

private boolean isPaused = false;

@Override
public void pause()
{
    this.isPaused = true;
}

@Override
public void run()
{
    while(!Thread.currentThread().isInterrupted())
    {
        // Do your work...

        // Check if paused
        if(this.isPaused)
        {
            try
            {
                Thread.sleep(10 * 1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}
}

和 PausableThread 接口:

public interface PausableThread
{
    void pause();
}

針對我的場景發布解決方案答案。

我創建了一個全局標志並將其用作開關。

所以現在,在數據庫交互之前我只是添加了一個條件[在線程執行各種作業的各種函數中,這解決了我擔心的實例問題]

if(isFlagChecked){thread.sleep(someDefinedTime);}

wait here if flag is true

continue with business logic...[db transacts here]

所以,我的問題就這樣解決了,盡管它不會暫停線程在中間狀態下運行,這是一件好事 - 少了一個麻煩。

並行,在我的觸發功能中 - 我檢查了經過的時間並在所需時間過去后將標志更改為 false。 檢查下面的代碼框架。

@async 
void pause() // triggered by parallel running app when required
{
   isFlagChecked=true;
   resumeTime=new Date(timeInMillis + (someDefinedTime)) // resume time to switch flag condition
   while (true) {
      if (new Date().compareTo(resumeTime) > 0) 
         isFlagChecked=false;
    }
}

經過嘗試和測試,一切運行良好,性能顯着提高[至少對我的場景]。

暫無
暫無

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

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