例如,请考虑以下情形。
App1:我有一个多线程Java应用程序,该应用程序在DB中输入了很多文件。
App2:当我使用其他一些应用程序访问数据库时,获取结果的速度很慢。
因此,当两个应用程序同时工作时,要花很长时间才能在前端应用程序2上获取数据库。
在这里,我想在App1上暂停所有事务(线程)一段“ x分钟”时间。考虑到使用应用2时已安装触发器。因此,当App2空闲时,App1将恢复运行,好像什么都没发生。请列出实现此目标的一些或一种最佳方法
Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) {
entry.getKey().sleep();
}
效果不好。
答案 0 :(得分:1)
只需尝试:
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();
}
答案 1 :(得分:0)
针对我的情况发布解决方案答案。
我创建了一个全局标志并将其用作开关。
现在,在数据库交互之前,我只是添加了一个条件[在线程执行各种作业的各种功能中,这解决了我担心的实例问题]
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;
}
}
经过测试,所有设备运行良好,性能显着提高了(对我而言,这至少是我的情况)。