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

标签 java multithreading threadpool executorservice threadpoolexecutor

我有一个线程池,它在我的主类中以 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/

相关文章:

java - 在 Java 中选择 ArrayList 中最后 25% 的对象

java - 如何为 servlet 请求提供 X 秒内返回的语义?

c# - 异步套接字读取 : the initiating thread must not be exited - what to do?

node.js - 我对 Node.js 中 libuv 线程池的理解是否正确?

java - 不能在Timer中的类的访问变量

java - 在 Ubuntu 中将 Matlab java 从 7 降级到 6 会返回错误

java - 我在添加数组的相同索引时得到空值

java - 如何将数组长度划分为长度为 3 倍数的数组

c++ - 析构函数和异步任务

java - 在 tomcat servlet 例程中使用异步 HTTP 客户端更好吗?