run two threads simultaneously with different sleep times
I have a situation to run thread1 every minute and thread2 every hour. How can i do this.
currently I have a working code to run thread1 after every minute.
main method
static void main(string args[]){
orderListner thread1 = new orderListner();
thread1.开发者_如何学运维start();
}
thread1
public static void orderListner extends thread{
public void run(){
while(true){
process();
thread.sleep(60000);
}
}
}
Now I need to start new thread for results which runs after every hour. how I can implement this simultaneously(thread1 will continously run thread2 should start every hour)
I suggest you use a ScheduledExecutorService
to centralize these tasks.
public final class ScheduledExecutorServiceDemo {
private static final ScheduledExecutorService exec =
Executors.newScheduledThreadPool(2);
public static void main(String[] args){
// Schedule first task
exec.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
// do stuff
}}, 0, 1, TimeUnit.MINUTES);
// Schedule second task
exec.scheduleAtFixedRate(new Runnable(){
@Override
public void run() {
// do stuff
}}, 0, 1, TimeUnit.HOURS);
}
}
well done so far! :)
you can just do the same again. what i mean by this is that you create a new class that represents your second thread (we can call this class SecondListener
). it should look like OrderListener
, but the sleep time should be changed to make it 1 hour.
then you just modify your main method so that it creates one object of the SecondListener class, and starts the thread, like you do with the OrderListener.
if it's important that the SecondListener doesn't run it's first run until after one hour, you can execute sleep before process in SecondListener.
and finally a small suggestion about sleep times: express them as equations for readability's sake. so instead of 60000, type 1000 * 60. and instead of 3600000 type 1000 * 60 * 60 :)
A better way to use to the thread class is to make an object that implements Runnable instead of extending thread. If you don't want to make another file, simply make an anonymous class. (It's a good habit to avoid using inheritance whenever possible.)
That being said, just make a new thread that runs on the hour and start it. I will use your method of threads instead.
static void main(string args[]){
orderListner thread1 = new orderListner();
orderListner2 thread2 = new orderListner2();
thread1.start;
thread2.start;
}
thread 1 is the same and thread 2 is
public static void orderListner2 extends thread{
void run(){
while(true){
process();
thread.sleep(3600000);
}
}
}
精彩评论