线程睡眠使其他线程等待

时间:2015-06-16 13:36:48

标签: java multithreading java-threads

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

以下是代码:

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立即启动。我必须发送欢迎短信然后密码短信(4分钟后)如何实现?

注意:两条短信都在4分钟之后出现

4 个答案:

答案 0 :(得分:4)

Thread.sleep(4 * 60 * 1000);

延迟执行当前运行的线程,在等待时间结束之前不执行q.start()。这个顺序没有意义。

答案 1 :(得分:1)

您的线程仅在

时创建
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

答案 2 :(得分:0)

您可以使用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();
}

在线程结束时&#34; q&#34;:

latch.countDown(); // stop to wait

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

答案 3 :(得分:-1)

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

您可能希望在GupShupSMSUtill()内发出睡眠(可能会将其签名更改为GupShupSMSUtill(PasswordSMS,MOB_NUM, sleeptime),以便能够控制睡眠时间。)