解决一般依赖关系的算法
想象一下,如果您有一堆相互依赖的方法(在本例中为 Java)。
- methodY 取决于 methodA、methodB、methodC
- methodX 依赖于 methodA、methodB
- 方法 B 取决于方法 A、方法 F
- methodT 不依赖于任何东西
- 方法 U 取决于方法 W
- 等等
如果methodA依赖于methodB,则意味着methodB必须在methodA执行之前先执行。
假设您不需要担心循环依赖。
每个方法都由一个线程运行,有一个固定大小的线程池.
如果不存在循环依赖,是否有可能最终都运行起来?
如何对线程进行排队以便所有线程最终都能运行?
例如,这不起作用
methodA 依赖于 methodB,methodC 依赖于 methodB,线程池大小为 2。如果我将 methodA 和 methodC 排队,它们将无限期地挂起,因为两者都在等待 methodB 但池已满。
Imagine if you have a bunch of methods (Java in this case) that depends on each other.
- methodY depends on methodA, methodB, methodC
- methodX depends on methodA, methodB
- methodB depends on methodA, methodF
- methodT doesnt depends on anything
- methodU depends on methodW
- and so on
If methodA depends on methodB that means methodB has to be executed first before methodA is executed.
Assume you do not need to worry about cyclic dependencies.
Each method is run by a Thread, there is a fixed size thread pool.
If there are no cyclic dependencies, is it possible for all of them to run eventually ?
How do I queue the threads so all of them would run eventually ?
For example this wouldn't work
methodA depends on methodB, methodC depends on methodB, thread pool size is 2. If I queue methodA and methodC, they would hang around indefinitely because both are waiting for methodB but pool is already full.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你想到这一点时,将线程和方法分开。方法是线程正在执行的内容。
您应该(在本例中)有 2 个可以执行任何方法的线程。他们将选择一个所有依赖项都已执行的方法,然后运行它。
重复此操作,直到方法队列为空。
顺便说一句,如果您被允许在所有依赖项完成后开始执行一个方法(我的意思是,如果您被允许将其留在队列中),那么逻辑是最简单的。
when you think about it, separate threads and methods. methods are what the threads are executing.
you should have (in this case) 2 threads that can execute any method. they will pick a method that all of it's dependencies have been executed, and run it.
repeat this until methods queue is empty.
btw, if you are allowed to start executing a method when all of it's dependencies are done (i mean, if you are allowed to leave it in the queue) then the logic is the most trivial.