是否可以在java中定义一组线程的执行顺序

我的理解是理论上的线程是并行执行的。 JVM决定; 当资源可用时,从等待的线程队列中挑选哪个线程(基于某种算法)。

因此,我们无法为线程提供/强制执行一系列执行。

假设我的java应用程序有3个线程,t1,t2和t3。

出于某些特定原因; 我希望线程按此顺序执行:t3然后是t1,然后是t2。

是否有可能做到这一点? java提供了这样做的任何方式吗?

使用执行者:

 executor.execute(runnable1); wait(); executor.execute(runnable2); wait(); executor.execute(runnable3); wait(); 

当然,每个Runnable都必须以notify()语句结束。

不要使用线程 ,是直截了当的答案。

如果您不希望代码无序运行,那么为什么要使用线程呢? 只需像往常一样一步一步地执行。

如果您希望线程的某些部分按顺序运行,那么使用标准并发机制,如锁,等待/通知和信号量,但如果您只是希望整个操作以特定顺序运行,那么…按顺序运行它们。 没有线程。

从Java 8开始,使用CompletableFuture变得非常简单:

 CompletableFuture.runAsync(runnable3) .thenRunAsync(runnable1) .thenRunAsync(runnable2); 

你不能告诉线程调度程序执行线程的顺序。如果你需要确保在线程A上运行的某段代码必须在线程B上运行的另一段代码之前运行,你必须使用锁或者强制执行该命令。 wait() / notify()

例如,您可以使用两个线程都可以访问的变量作为“标志”来指示线程B是否可以安全继续。 线程B可以在循环中wait() ,检查该变量的值。 然后,当线程B运行安全时,线程A可以使用notify()设置变量并唤醒线程B。

所以,是的,可以在不同线程上发生的事情之间强制执行所需的顺序。 但是,通常,您希望避免编写这样的低级详细代码。 这很容易弄错,导致细微的,难以发现的错误。 在处理multithreading代码时,如果可以,请始终尝试使用高级构建块。

你可以在另一个线程上加入一个线程,这样当另一个线程完成时它就会运行。

您可以为线程设置顺序。

我试图模拟你的情况:

 public class ThreadJoinExample { private static final Thread FIRST = new Thread( new RunnableImpl(), "first" ); private static final Thread SECOND = new Thread( new RunnableImpl(), "second" ); public static void main(String[] args) { //here have started current thread or "main" thread that will control above threads FIRST.start(); //waiting 2 seconds, "stop" your current thread and after current thread will start this "t3" thread until it will dead try { FIRST.join(2000); } catch (InterruptedException e) { System.out.println(); e.printStackTrace(); } SECOND.start(); //"stop" your current thread immediately and run "t1" thread until it will dead. try { SECOND.join(); } catch (InterruptedException e) { e.printStackTrace(); } //Or we can wait for all threads and in the end - finish current main thread try { FIRST.join(); SECOND.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Current thread is going die"); } } class RunnableImpl implements Runnable{ @Override public void run() { System.out.println("Started thread: "+Thread.currentThread().getName()); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread is going die: "+Thread.currentThread().getName()); } } 

输出:

 Started thread: first Started thread: second Thread is going die: first Thread is going die: second Current thread is going die 

摘要:使用.join()方法,我们可以将当前线程移动到Runnable状态,直到“join thread”死亡