lundi 21 avril 2014

Java - puis-je utiliser attendre au lieu de sommeil ? -Débordement de pile


I came across a question in which the poster tried to have a thread wait for a second. They were using wait, but outside a synchronized block, and therefore it crashed.


Given a running thread, to pause the execution for a given time, one would do:


Thread.sleep(1000);

This should work as well, and have very similar result:


synchronized(this) {
this.wait(1000);
}

Using the wait timeout, the thread will unpause 1 second later.


The question is this: if I don't have any monitoring and notifying issue, is there an actual reason to use one over the other?




The difference is pretty clear in the javadoc


void Object.wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.


void Object.wait(long timeout) : Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.


static void Thread.sleep(long millis) Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.


Otherwise, the question is asked and got an explained answer here .



I came across a question in which the poster tried to have a thread wait for a second. They were using wait, but outside a synchronized block, and therefore it crashed.


Given a running thread, to pause the execution for a given time, one would do:


Thread.sleep(1000);

This should work as well, and have very similar result:


synchronized(this) {
this.wait(1000);
}

Using the wait timeout, the thread will unpause 1 second later.


The question is this: if I don't have any monitoring and notifying issue, is there an actual reason to use one over the other?



The difference is pretty clear in the javadoc


void Object.wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.


void Object.wait(long timeout) : Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.


static void Thread.sleep(long millis) Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.


Otherwise, the question is asked and got an explained answer here .


0 commentaires:

Enregistrer un commentaire