【问题标题】:Pausing thread pool on user input java在用户输入java上暂停线程池
【发布时间】:2014-07-24 05:37:24
【问题描述】:

我有一个线程池,它在我的主类中使用 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 状态,如果它设置为暂停以跳过其执行指令,尽管它不起作用。是否有任何适当的方法可以根据我的用户输入暂停和恢复我的线程。

谢谢

【问题讨论】:

    标签: java multithreading threadpool executorservice threadpoolexecutor


    【解决方案1】:

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

    示例:

    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;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2018-11-04
      • 1970-01-01
      • 2015-02-21
      相关资源
      最近更新 更多