是否可以在Java中为一组线程定义执行顺序 [英] is it possible to define execution order for a set of threads in java
问题描述
我的理解是,理论上线程是并行执行的. JVM决定;当有资源可用时(根据某种算法)从等待线程队列中选择哪个线程.
My understanding is that threads in theory are executed in parallel. JVM decides; when a resource is available which thread to pick from the waiting thread queue (based on some algorithm).
因此,我们不能为线程提供/强制执行序列.
Hence we can not provide/enforce a sequence of execution for threads.
说我的Java应用程序有3个线程,t1,t2和t3.
Say my java application has 3 threads, t1, t2 and t3.
出于某些特定原因;我希望线程按此顺序执行: t3然后t1然后t2.
For some specific reason; I want the threads to execute in this order: t3 then t1 and then t2.
是否可以这样做? java是否提供了这样做的任何方式?
Is it possible to do this? Does java provided any way of doing this?
推荐答案
使用执行程序:
executor.execute(runnable1);
wait();
executor.execute(runnable2);
wait();
executor.execute(runnable3);
wait();
当然,每个Runnable必须以notify()
语句结尾.
And of course, each Runnable has to end with a notify()
statement.
这篇关于是否可以在Java中为一组线程定义执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!