Wait and policy must perform operations on the same object.
Code 1:
- Package wait1_y1;
- Public class threadinstance implements runnable {
- Public void run (){
- Double D = 0;
- Synchronized (this ){
- Try {
- Thread. Sleep (5000 );
- } Catch (interruptedexception e ){
- E. printstacktrace ();
- }
- For (INT I = 0; I <1000; I ++ ){
- D + = I;
- }
- System. Out. println (d );
- Notify ();
- // If there is another sleep code, the other party will not immediately reply from wait even if commit y is called,
- // Because the synchronized has not been completed, after all, it uses the object called by wait.
- /* Try {
- Thread. Sleep (5000 );
- } Catch (interruptedexception e ){
- E. printstacktrace ();
- }*/
- }
- }
- }
Let's test the above example:
- Package wait1_y1;
- Public class testwaitpolicy {
- Public static void main (string [] ARGs ){
- Threadinstance Ti = new threadinstance ();
- Thread t = new thread (Ti );
- T. Start ();
- Synchronized (t ){
- Try {
- System. Out. println ("waiting ...");
- T. Wait ();
- System. Out. println ("they have finished running and don't have to wait. ");
- } Catch (exception e ){
- E. printstacktrace ();
- }
- }
- }
- }
Run the test case above and get the test result:
Bytes ---------------------------------------------------------------------------------------------------------------
Waiting... (note that the following statement is not printed immediately after printing in this line. It is printed only when the thread sleep time in the case program ends)
499500.0
They are running and don't have to wait.
Bytes ---------------------------------------------------------------------------------------------------------------