Using wait in Java requires a synchronous lock, and 2 threads must all use a synchronous block of code, otherwise the exception

Source: Internet
Author: User

The caption already shows that the default lock is not the lock of the synchronization code block when the Child Thread Wai (), so the indicated lock displayed at wai time is now interpreted by the code:

public class Test {//staticboolean flag=true;public static void Main (string[] args) throws Interruptedexception {Zp z=new Zp (); Thread st=new thread (z); St.start (); for (int x=0;x<100000;x++) {if (x%5000==0) {//flag=false; Thread.Sleep (+); synchronized (Test.class)//The synchronization must be determined here, otherwise when the child thread does not discard the lock, the exception will be executed below {Test.class.notify ();}}} Static class Zp implements runnable{@Overridepublic void Run () {synchronized (Test.class) {while (true) {for (int x=0;x< 10;x++) {System.out.println ("haha ...");} try {Test.class.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}}}}}

  

Using wait in Java requires a synchronous lock, and 2 threads must all use a synchronous block of code, otherwise the exception

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.