Wait and notify instances

Source: Internet
Author: User

Wait and policy must perform operations on the same object.

 

Code 1:

  1. Package wait1_y1;
  2. Public class threadinstance implements runnable {
  3. Public void run (){
  4. Double D = 0;
  5. Synchronized (this ){
  6. Try {
  7. Thread. Sleep (5000 );
  8. } Catch (interruptedexception e ){
  9. E. printstacktrace ();
  10. }
  11. For (INT I = 0; I <1000; I ++ ){
  12. D + = I;
  13. }
  14. System. Out. println (d );
  15. Notify ();
  16. // If there is another sleep code, the other party will not immediately reply from wait even if commit y is called,
  17. // Because the synchronized has not been completed, after all, it uses the object called by wait.
  18. /* Try {
  19. Thread. Sleep (5000 );
  20. } Catch (interruptedexception e ){
  21. E. printstacktrace ();
  22. }*/
  23. }
  24. }
  25. }

Let's test the above example:

 

  1. Package wait1_y1;
  2. Public class testwaitpolicy {
  3. Public static void main (string [] ARGs ){
  4. Threadinstance Ti = new threadinstance ();
  5. Thread t = new thread (Ti );
  6. T. Start ();
  7. Synchronized (t ){
  8. Try {
  9. System. Out. println ("waiting ...");
  10. T. Wait ();
  11. System. Out. println ("they have finished running and don't have to wait. ");
  12. } Catch (exception e ){
  13. E. printstacktrace ();
  14. }
  15. }
  16. }
  17. }

 

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 ---------------------------------------------------------------------------------------------------------------

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.