简体   繁体   中英

Client Server Pausing/Resuming/Closing with Thread State

So I have a client running that I'm trying to pause/resume or close when given a certain input. If "!" is entered, then it pauses the thread or resumes the thread depending on if it was running or not. And if "#" is entered whether its running or not, the thread is closed.

I think I am close, but I am having a little trouble. Heres my code:

while(true) {
                Thread.State state = t.getState();
                if(state == Thread.State.RUNNABLE) {
                    if(input.nextLine().equals("!")) {
                        t.suspend();
                        System.out.println("Sleeping");
                        System.out.println(state);
                    }
                    else if(input.nextLine().equals("#")) {
                        t.stop();
                        System.out.println("Closing");
                        System.out.println(state);
                    }
                }
                if(state == Thread.State.TIMED_WAITING) {
                    if(input.nextLine().equals("!")) {
                        t.resume();
                        System.out.println("Resuming");
                        System.out.println(state);
                    }
                    else if(input.nextLine().equals("#")) {
                        t.stop();
                        System.out.println("Closing");
                        System.out.println(state);
                    }
                }
            }

            }

This code kind of works. But if I want to close the thread, I have to enter # twice for it to close.

I think you are far from good.

You should avoid any using of Thread#pause() , Thread#resume() and Thread.stop() especially Thread.stop(). They are deprecated functions and sooner or later many be not implemented in future version of JDK.

The suggested way to implement what you want it to send a signal (optionally, an addition interrupt) to the thread, and the thread itself aware of signal change and do enter the target state by itself.

Ref: Why is Thread.stop deprecated?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM