Call function every x time without blocking the GUI Java

后端 未结 3 1767
余生分开走
余生分开走 2021-01-23 02:31

I have a class caled ItemGUI which is handling everything related with the user interface. The user, is able to add some links, which are the items, so when he inserts a link an

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-23 03:22

    First off, I'm in no way sure how this should be done, but I think I have a suggestion for how you could make it work. In a project I'm working on at the moment I use ExecutorService to handle my thread pool. I have to mention here, that I started working with threads in Java a little over a week ago myself, so I apologize if what I'm suggestion is too basic or wrong.

    My suggestion is, that you could create a static boolean variable that you could use for controlling your loop. Code could look something like this:

    public static boolean isRunning;
    
    public static void main(String[] args) {
    
        ExecutorService executerService = Executors.newCachedThreadPool();
    
        executerService.execute(new Runnable() {
            @Override
            public void run() {
                isRunning=true;
                while (isRunning){
                    System.out.println("hello world"); //Your loop here
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    

    Whenever you set the isRunning boolean to false the loop will stop, and the Thread will finish after a little while.

    As for observer-observable classes I don't know this and I'm not sure I understand your last question.

提交回复
热议问题