Search code examples
javamultithreadingjava-threads

Thread Sleep Makes Other Threads Wait


I have a task where while generating a random password for user the SMS should go after 4 MIN, but the welcome SMS should go immediately. Since password I am setting first and need to send after 4 MIN I am making that thread sleep (Cant use ExecutorServices), and welcome SMS thread start.

Here is the code:

String PasswordSMS="Dear User, Your password is "+'"'+"goody"+'"'+" Your FREE 
recharge service is LIVE now!";
String welcomeSMS="Dear goody, Welcome to XYZ";
         try {          
            Thread q=new Thread(new GupShupSMSUtill(PasswordSMS,MOB_NUM));
            Thread.sleep(4 * 60 * 1000);
            q.start();
             GupShupSMSUtill sendWelcomesms2=new GupShupSMSUtill(welcomeSMS, MOB_NUM);
                Thread Bal3=new Thread(sendWelcomesms2);
                Bal3.start();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

</code> 

So if I change the order the thread sendWelcomesms2 Immediately starts.I have to send welcome SMS then password sms (After 4 Min) how its achievable ??

NOTE: Both SMS come after 4 MIN


Solution

  • Thread.sleep(4 * 60 * 1000);
    

    delays execution of your currently running thread, your q.start() is not executed until the wait time is over. This order doesn't make sense.