如何无限期地在Java中暂停一个线程然后恢复它? [英] How to indefinitely pause a thread in Java and later resume it?
问题描述
也许这个问题之前已被多次询问过,但我从未找到过令人满意的答案。
Maybe this question has been asked many times before, but I never found a satisfying answer.
问题:
我必须使用循环策略模拟进程调度程序。我正在使用线程来模拟进程和多道程序设计;一切正常,JVM管理线程。但问题是,现在我想控制所有线程,这样我就可以通过一定量(或时间)单独运行每个线程,就像真正的OS进程调度程序一样。
The problem:
I have to simulate a process scheduler, using the round robin strategy. I'm using threads to simulate processes and multiprogramming; everything works fine with the JVM managing the threads. But the thing is that now I want to have control of all the threads so that I can run each thread alone by a certain quantum (or time), just like real OS processes schedulers.
我在想做什么:
我希望有一个所有线程的列表,因为我迭代列表我想为每个线程执行相应的量程,但是一旦时间到了我想要无限期地暂停该线程直到所有线程列表中的线程被执行,然后当我到达同一个线程时再次恢复它,依此类推。
What I'm thinking to do:
I want have a list of all threads, as I iterate the list I want to execute each thread for their corresponding quantum, but as soon the time's up I want to pause that thread indefinitely until all threads in the list are executed and then when I reach the same thread again resume it and so on.
问题:
所以他们是一种方法,不使用弃用的方法stop(),suspend()或resume()来控制线程吗?
The question:
So is their a way, without using deprecated methods stop(), suspend(), or resume(), to have this control over threads?
推荐答案
谁说Java不够低?
Who said Java is not low level enough?
这是我的3分钟解决方案。我希望它符合您的需求。
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<RoundRobinProcess> threadList = new ArrayList<RoundRobinProcess>(); 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.
这篇关于如何无限期地在Java中暂停一个线程然后恢复它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!