线程休眠使其他线程等待

Thread Sleep Makes Other Threads Wait

我有一个任务,在为用户生成随机密码时,短信应该在 4 分钟后发送,但欢迎短信应该立即发送。由于密码是我首先设置的,需要在 4 分钟后发送,我正在让该线程休眠(不能使用 ExecutorServices),欢迎 SMS 线程启动。

代码如下:

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> 

因此,如果我更改线程 sendWelcomesms2 的顺序,立即 starts.I 必须发送欢迎短信,然后发送密码短信(4 分钟后)如何实现?

注意:两条短信都在 4 分钟后收到

Thread.sleep(4 * 60 * 1000);

延迟当前 运行 线程的执行,您的 q.start() 直到等待时间结束后才会执行。这个顺序没有意义。

在为 q 发出 start 命令之前,您正在休眠当前线程。

您可能想在 GupShupSMSUtill() 中发出睡眠(也许将其签名更改为 GupShupSMSUtill(PasswordSMS,MOB_NUM, sleeptime) 之类的东西,以便能够控制它睡眠的时间)。

您的主题仅在

时创建
Thread q=new Thread(new GupShupSMSUtill(PasswordSMS,MOB_NUM));

被执行。您的话题在

时开始
q.start();

被执行。所以如果你想在主线程休眠时实现 运行 q 线程,你应该按以下顺序编写你的行:

        Thread q=new Thread(new GupShupSMSUtill(PasswordSMS,MOB_NUM)); // Create thread
        q.start(); // start thread
        Thread.sleep(4 * 60 * 1000); // suspend main thread for 4 sec

您可以使用 join():

String PasswordSMS = "Dear User, Your password is " + "\"" + "goody" + "\"" + " Your FREE recharge service is LIVE now!";
String welcomeSMS = "Dear goody, Welcome to XYZ";
try
{
    GupShupSMSUtill sendWelcomesms2 = new GupShupSMSUtill(welcomeSMS, MOB_NUM);
    Thread Bal3 = new Thread(sendWelcomesms2);
    Bal3.start();
    Thread q = new Thread(new GupShupSMSUtill(PasswordSMS, MOB_NUM));
    q.start();
    q.join();
}
catch (InterruptedException e)
{
    e.printStackTrace();
}

或闩锁:

private static java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1);

和代码:

String PasswordSMS = "Dear User, Your password is " + "\"" + "goody" + "\"" + " Your FREE recharge service is LIVE now!";
String welcomeSMS = "Dear goody, Welcome to XYZ";
try
{
    GupShupSMSUtill sendWelcomesms2 = new GupShupSMSUtill(welcomeSMS, MOB_NUM);
    Thread Bal3 = new Thread(sendWelcomesms2);
    Bal3.start();
    Thread q = new Thread(new GupShupSMSUtill(PasswordSMS, MOB_NUM));
    q.start();
    latch.await(); // Wait
}
catch (InterruptedException e)
{
    e.printStackTrace();
}

线程结束时"q":

latch.countDown(); // stop to wait

提示 - 在这种情况下不要使用 Thread.sleep(x)。