Reputation: 5325
I got the the difference between Thread.sleep() and wait().
The code sleep(1000);
puts thread aside for exactly one second.
The code wait(1000);
causes a wait of up to one second.
What exactly does it mean other than wait is in object class and sleep in Thread class?
Is there any good example available?
Upvotes: 0
Views: 73
Reputation: 77177
You call wait()
on an object you've synchronized on, and it releases the monitor and waits for a notify()
or notifyAll()
to be called on that same object. It's usually used to coordinate activity on some shared object, such as a request or connection queue.
sleep()
doesn't release any monitors or otherwise interact directly with other threads. Instead, it retains all monitors and simply stops executing the current thread for a little bit.
Upvotes: 6
Reputation: 1595
wait()
may be awaken by calling notify()
or notifyAll()
.
In this example, you can see as Blah1 doesn't wait 1000 miliseconds because it's awaken by Blah2 earlier. Blah2 waits.
wait()
method releases monitor which is blocked by given thread. sleep()
doesn't.
sleep()
can be interrupted by calling interrupt()
method.
public class Blah implements Runnable {
private String name;
public Blah(String name) {
this.name = name;
}
synchronized public void run() {
try {
synchronized (Blah.class) {
System.out.println(name + ": Before notify " + new Date().toString());
Blah.class.notifyAll();
System.out.println(name + ": Before wait " + new Date().toString());
Blah.class.wait(1000);
System.out.println(name + ": After " + new Date().toString());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread th1 = new Thread(new Blah("Blah1"));
Thread th2 = new Thread(new Blah("Blah2"));
th1.start();
th2.start();
}
}
Output:
Blah1: Before notify Tue Jan 13 09:19:09 CET 2015
Blah1: Before wait Tue Jan 13 09:19:09 CET 2015
Blah2: Before notify Tue Jan 13 09:19:09 CET 2015
Blah2: Before wait Tue Jan 13 09:19:09 CET 2015
Blah1: After Tue Jan 13 09:19:09 CET 2015
Blah2: After Tue Jan 13 09:19:10 CET 2015
Upvotes: 1