[英]Pausing thread pool on user input java
I have a threadpool which runs with a while loop in my main class 我的主类中有一个使用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();
}
Although I'm not sure how to go about actually pausing my runnables when I get the user input. 尽管我不确定在获得用户输入后如何暂停我的可运行对象。 I had tried checking the forcePause status of this code from thread / runnable class file, and if it is set to pause to skip its execution instructions although it was not working. 我曾尝试从线程/可运行类文件中检查此代码的forcePause状态,并且将其设置为暂停以跳过其执行指令,尽管它不起作用。 Is there any proper way to go about pausing and resuming my threads based on my user input. 是否有任何适当的方法可以根据我的用户输入暂停和恢复我的线程。
Thanks 谢谢
You code is fine, you should just abstract it out a bit more so you can catch exceptions. 您的代码很好,您应该对其进行抽象,以便您可以捕获异常。
Example: 例:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.