converting to ScheduledThreadPoolExecutor

后端 未结 1 1613
日久生厌
日久生厌 2020-12-29 16:11

I am still a beginner at Java so I have not learned much about threads and concurrency. However, I would like to be able to use the ScheduledThreadPoolExecutor as a timer b

相关标签:
1条回答
  • 2020-12-29 16:48

    Replace

    Timer timer = new Timer();
    

    with

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    

    and

    class Task extends TimerTask
    

    with

    class Task implements Runnable
    

    and

    timer.scheduleAtFixedRate(new Task(), 0, 1000);
    

    with

    service.scheduleAtFixedRate(new Task(), 0, 1000, TimeUnit.MILLISECONDS);
    

    BTW You should not be attempting to update the GUI on another thread. Instead you have to add a task to the Swing GUI Thread to perform the task

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                textOut.setText("" + i++);
            }
        });
    
    0 讨论(0)
提交回复
热议问题