java - 暂停所有 运行 线程一段时间

java - Pausing all running threads for some time

例如考虑以下场景。

App1: 我有一个多线程的java应用程序,它在数据库中输入了很多文件。

App2:当我使用其他应用程序访问数据库时,获取结果很慢。

因此,当两个应用程序同时工作时,前端应用程序 2 上的数据库获取结果会花费大量时间。

在这里,我想暂停 App1 上的所有事务(线程)一些 'x min' 时间。考虑到在使用应用程序 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();
    }
}

你的话题 class 将是这样的:

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;
    }
}

经过尝试和测试,一切都运行很好,性能显着提高[对我的场景而言最少]。