gpt4 book ai didi

java - 在用户输入java上暂停线程池

转载 作者:行者123 更新时间:2023-12-01 12:54:01 24 4
gpt4 key购买 nike

我有一个线程池,它在我的主类中以 while 循环运行

   executor = Executors.newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
Runnable crawl = new crawlThread(this);
executor.execute(crawl);
}
executor.shutdown();

try {
while (!executor.isTerminated()) {
Thread.sleep(1000);
this.liveStatus();

if (System.in.available() != 0) {

System.out.println("What would you like to do? (0 = quit, 1 = pause, 2 = resume)");

Scanner runinput = new Scanner(System.in);
Integer answer = runinput.nextInt();
if (answer == 0)
{
System.out.println("Quitting...");
break;
} else if (answer == 1)
{
this.forcePause = true;
System.out.println("Pausing...");
} else if (answer == 2)
{
this.forcePause = false;
System.out.println("Resuming...");
}
runinput.close();
}

}
} catch (Exception e) {
e.printStackTrace();
}

虽然我不确定当我收到用户输入时如何实际暂停我的可运行对象。我曾尝试从线程/可运行类文件检查此代码的forcePause状态,以及是否将其设置为暂停以跳过其执行指令,尽管它不起作用。是否有任何正确的方法可以根据我的用户输入暂停和恢复我的线程。

谢谢

最佳答案

你的代码很好,你应该把它抽象一点,这样你就可以捕获异常。

示例:

class MyThread extends Thread {

private volatile boolean running = true; // Run unless told to pause

...

@Override
public void run()
{
for(int i=0 ; ; i++)
{

// This is a crude implementation of pausing the thread
while (!running)
// Work

area.setText(i+"");
}

public void pauseThread() throws InterruptedException
{
running = false;
}

public void resumeThread()
{
running = true;
}

}

关于java - 在用户输入java上暂停线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24022713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com