-3

我有一项任务,在为用户生成随机密码时,SMS 应该在 4 分钟后发送,但欢迎 SMS 应该立即发送。由于我首先设置密码并且需要在 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 立即启动的顺序。我必须发送欢迎短信然后密码短信(4 分钟后)如何实现?

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

4

4 回答 4

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

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

于 2015-06-16T13:39:54.810 回答
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
于 2015-06-16T13:44:10.950 回答
0

您可以使用加入():

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)。

于 2015-06-19T15:40:05.773 回答
-1

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

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

于 2015-06-16T13:43:45.443 回答