prranay
prranay

Reputation: 1889

Does use of sleep guarantees execution sequence of a Thread?

Does below code snippet guarantees that t1, T2 and T3 will start executing in sequence?

public class ThreadExecDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new ThreadDemo(),"t1");
        Thread t2 = new Thread(new ThreadDemo(),"t2");
        Thread t3 = new Thread(new ThreadDemo(),"t3");
        t1.start();
        Thread.sleep(5);
        t2.start();
        Thread.sleep(5);
        t3.start();
    }
}

class ThreadDemo implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" is running ");
    }
}

Upvotes: 0

Views: 185

Answers (3)

John Zhu
John Zhu

Reputation: 151

I can't add a comment yet so posting here: there is actually quite a decent stack overflow answer about executing threads in sequence here running 3 threads in sequence java

Check the generic solution with "class RunThreadsInOrder" does what you want using synchronized lock.

Upvotes: 0

Collateral.dmg
Collateral.dmg

Reputation: 128

As @Nathan Hughes said, no, there is no guarantee that the threads will start executing in a sequence.

Reasoning: Sleep() blocks the current thread for the number of timeslices that can occur within the specified number of milliseconds. However, the length of a timeslice is actually different on certain versions of Windows or Processors. As a result, Sleep() is not useful for timing or, in your case, trying to execute threads in a specific sequence

Try to avoid using Sleep() - in my opinion, Sleep is only useful for simulating lengthy or calculation intensive operations while testing/debugging

Upvotes: 1

Jesper Juhl
Jesper Juhl

Reputation: 31475

Short answer: No.

Longer answer: No. You cannot influence the scheduling of threads reliably by sleeping (why would you even want to?). When you start a thread it runs asynchronously to any other thread (including the main thread) and you have no control over when it is scheduled. Nor should you care.

Upvotes: 4

Related Questions