例如,考虑以下场景。
App1:我有一个多线程java应用程序,它在数据库中输入很多文件。
App2:当我使用其他应用程序访问数据库时,获取结果的速度很慢。
因此,当两个应用程序同时工作时,前端应用程序需要花费大量时间来获取数据库结果。
在这里,我想将 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接口(interface):
public interface PausableThread
{
void pause();
}
关于java - 暂停所有正在运行的线程一段时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59097946/