How to indefinitely pause a thread in Java and later resume it?

前端 未结 3 529
醉梦人生
醉梦人生 2020-12-13 14:52

Maybe this question has been asked many times before, but I never found a satisfying answer.

The problem:


I have to simulate a process s

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 15:20

    Who said Java is not low level enough?

    Here is my 3 minute solution. I hope it fits your needs.

    import java.util.ArrayList;
    import java.util.List;
    
    public class ThreadScheduler {
    
        private List threadList
                = new ArrayList();
    
        public ThreadScheduler(){
            for (int i = 0 ; i < 100 ; i++){
                threadList.add(new RoundRobinProcess());
                new Thread(threadList.get(i)).start();
            }
        }
    
    
        private class RoundRobinProcess implements Runnable{
    
            private final Object lock = new Object();
            private volatile boolean suspend = false , stopped = false;
    
            @Override
            public void run() {
                while(!stopped){
                    while (!suspend){
                        // do work
                    }
                    synchronized (lock){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                }
            }
    
            public void suspend(){
                suspend = true;
            }
            public void stop(){
                suspend = true;stopped = true;
                synchronized (lock){
                    lock.notifyAll();
                }
            }
    
            public void resume(){
                suspend = false;
                synchronized (lock){
                    lock.notifyAll();
                }
            }
    
        }
    }
    

    Please note that "do work" should not be blocking.

提交回复
热议问题