is it possible to define execution order for a set of threads in java

后端 未结 6 1879
离开以前
离开以前 2021-01-26 00:10

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

6条回答
  •  长发绾君心
    2021-01-26 00:43

    You can set order for your threads.

    I've tried to modelling your situation:

    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());
        }
    }
    

    Output:

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

    summary: With .join() method we can move current thread to Runnable state until the time when "joined thread" will dead

提交回复
热议问题