1. For the Sleep () method, we first need to know that the method belongs to the thread class. The wait () method is part of the object class.
2. The sleep () method causes the program to pause execution for a specified time, giving up the CPU to other threads, but his monitoring state remains, and when the specified time is up, it automatically resumes its running state. During the call to the Sleep () method, the thread does not release the object lock. when the Wait () method is called, the thread discards the object lock, enters the waiting lock pool waiting for the object, and the thread only enters the object lock pool when the Notify () method is called for this object .
Gets the object lock into the running state.
eg
public class Testthread {
public static void Main (String [] args)
{
New Thread (New Thread1 ()). Start ();
try {
Thread.Sleep (5000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
New Thread (New Thread2 ()). Start ();
}
private static class Thread1 implements runnable{
@Override
public void Run () {
Synchronized (Testthread.class)
{
SYSTEM.OUT.PRINTLN ("Thread one start .....") ");
SYSTEM.OUT.PRINTLN ("Thread One Wait ...");
try {
TestThread.class.wait ();
} catch (Exception e) {
Todo:handle exception
}
SYSTEM.OUT.PRINTLN ("Thread one runs here .....") ");
SYSTEM.OUT.PRINTLN ("Thread one end ...");
}
}
}
private static class Thread2 implements runnable{
@Override
public void Run () {
Synchronized (Testthread.class) {
System.out.println ("thread2 start ....");
System.out.println ("Thread2 is sleep ....");
Only after the Notify () method is called for this object does the thread enter the object lock pool to get the object lock into the running state.
TestThread.class.notify ();
//==================
Difference
If we put the code: TestD.class.notify (), commented out, that is, Testd.class called the Wait () method, but did not call notify ()
method, the thread is always in a pending state.
try {
The sleep () method causes the program to pause execution for the specified time, yielding the CPU to other threads,
But his monitoring status is still maintained, and when the specified time is up, it will automatically return to the running state.
During the call to the sleep () method, the thread does not release the object lock.
Thread.Sleep (5000);
} catch (Exception e) {
E.printstacktrace ();
}
System.out.println ("Thread2 is going on ....");
System.out.println ("THREAD2 is over!!!");
}
}
}
}
Results:
Thread one start .....
Thread a wait .....
Thread2 start ....
Thread2 is sleep ....
Thread2 is going on ....
THREAD2 is OVER!!!
Thread one runs here .....
Thread one end .....
If the code is commented out:
TestThread.class.notify ();
Results:
Thread one start .....
Thread a wait .....
Thread2 start ....
Thread2 is sleep ....
Thread2 is going on ....
THREAD2 is OVER!!!
The difference between sleep () and wait () in Java