在无限循环中暂停并重新启动线程

时间:2015-11-09 13:25:56

标签: java multithreading

我需要的要求如下所示。

  • 我有一个jsp包含启用和禁用单选按钮。
  • 如果我点击启用,则应该按照每隔2或3小时的时间间隔执行一个进程。
  • 如果单击并提交禁用,则为 当前执行任务应暂停,直到再次启用 从jsp中提交/单击(如果启用,则应执行上述步骤 继续执行)。

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
    
    
        //first time execution
        if(request.getParameter("lic").equals("enable") && counter==0)
        {
            t1.start();
            counter++;
            System.out.println(counter);
        }
    
    
        //if already started and clicks re-enable
        else if(request.getParameter("lic").equals("enable") && counter>0)
        {
            System.out.println("thread already started");
            t1.interrupt();
        }
    
        //for long pausing of thread
        else if(request.getParameter("lic").equals("disable"))
        {
            System.out.println("thread is going to pause");
            try 
            {
                Thread.sleep(20000);
                System.out.println("slept for 20 seconds");
            } 
            catch (InterruptedException e) 
            {
                // TODO Auto-generated catch block
                System.out.println("interrupted while sleeping");
            }
    
        }
    }
    static int counter = 0;
    static Thread t1 = new Thread()
    {
        public void run()
        {
            System.out.println("hi thread is executed");
        }   
    };
    

    }

0 个答案:

没有答案