java - 如何保证线程的执行顺序

标签 java multithreading thread-synchronization

这个问题在这里已经有了答案:





How threads are executed in the memory?

(2 个回答)


1年前关闭。




这是问题的简化版本。给定 n线程数,每个线程始终打印一个常数。例如,Thread-1应始终打印 1 , Thread-2应始终打印 2等等...
如何确保线程按顺序执行,即输出应如下所示:

Thread-1: 1
Thread-2: 2
Thread-3: 3
.
.
.
Thread-n: n
我有一个天真的解决方案,可以通过 wait()/notify()但我想可能有比这更好的解决方案。也许,使用 Semaphore也许?我不知道。
更新 :
根据收到的答案,我想我不是很清楚。有一些限制:
  • 所有线程都应该立即启动(假设我们真的无法控制)
  • 一旦所有线程启动,线程之间应该有某种通信以按顺序执行。
  • 最佳答案

    使用 Thread.join() 可以很好地处理线程的这种顺序执行。方法。要正确处理它,您可能必须创建 MyRunnable (或者,使用您喜欢的任何名称)实现 Runnable界面。内部 MyRunnable , 你可以注入(inject)一个 parent Thread , 并调用 parent.join()MyRunnable.run() 的顶部方法。代码如下:

    public class SequentialThreadsTest {
    
        static class MyRunnable implements Runnable {
            static int objCount; // to keep count of sequential object
    
            private int objNum;
            private Thread parent; // keep track of parent thread
            
            MyRunnable(Thread parent) {
                this.parent = parent;
                this.objNum = objCount + 1;
                objCount += 1;
            }
    
            @Override
            public void run() {
                try {
                    if(parent != null) {
                        parent.join();
                    }
                    System.out.println("Thread-" + objNum + ": " + objNum);
    
                } catch(InterruptedException e) {
                    e.printStackTrace();
                    // do something else
    
                } finally {
                    // do what you need to do when thread execution is finished
                }
            }
        }
    
        public static void main(String[] args) {
            int n = 10;
            
            Thread parentThread = null;
    
            for(int i=0; i<n; i++) {
                Thread thread = new Thread(new MyRunnable(parentThread));
                thread.start();
    
                parentThread = thread;
            }
        }
    }
    
    输出是:
    Thread-1: 1
    Thread-2: 2
    Thread-3: 3
    Thread-4: 4
    Thread-5: 5
    Thread-6: 6
    Thread-7: 7
    Thread-8: 8
    Thread-9: 9
    Thread-10: 10
    

    关于java - 如何保证线程的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63252957/

    相关文章:

    java - 按下按钮时启动无限循环线程,再次按下按钮时停止

    java - 如何在 Android 中为 fragment 添加标题

    java - object.wait 和 Thread.sleep() 的 CPU 周期

    android - 从 OpenGL 线程使用时 Handler.dispatchMessage 挂起/崩溃

    java - java中的背景图像

    java - Spring 父级的依赖项中缺少版本

    c - GTK+ system(3) 线程调用

    java - 线程和上下文之间的问题 - Android

    c - 使用互斥锁进行 Pthread 同步

    java - 如何在不使用同步(无锁序列计数器实现)的情况下修复竞争条件?