Java Multithreading (thread communication-waiting for a new mechanism-code optimization)

Source: Internet
Author: User

The wait-and-wake mechanism involves methods:

Wait (): The thread is frozen and the wait thread is stored in the thread pool.

NOTICFY (): Wakes up one thread in the same thread pool (any thread that may also be the current wait)

Notifyall (): Wakes all threads in the same thread pool.

These methods must be defined in synchronization, because this method is used to manipulate the thread state, and it must be clear which locked thread to operate on.

Why Wait,notify,notifyall is defined in the object class as a method of manipulating threads.

Because these methods are the monitor (lock) method, the monitor is a lock.

A lock is an arbitrary object, and the method called by any object is in the object class.

Class resource{

private String name;
Private String sex;
Private Boolean flag = false;

Public synchronized void Set (string name, string sex) {
if (flag) {
Try{wait ();} catch (Exception e) {}
}
Notify ();
THIS.name = name;
This.sex = sex;
System.out.println (this.name+ "**input*" +this.sex);
Flag = true;

}
Public synchronized void out () {
if (!flag) {
Try{wait ();} catch (Exception e) {}
}
Notify ();
System.out.println (this.name+ "**output*" +this.sex);
Flag = false;

}
}

Class Input implements Runnable {
Resource s;
Input (Resource t) {
THIS.S = t;
}
int i = 0;
public void Run () {
while (true) {
if (i ==0) {
S.set ("Mike", "Man");
}else{
S.set ("Xixi", "women");
}
i= (i+1)% 2;
}
}
}
Class Output implements runnable{
Resource s;
Output (Resource t) {
THIS.S = t;
}
public void Run () {
while (true) {
S.out ();
}
}

}

Class resourcedemo{
public static void Main (string[] arg) {
Resource s = new Resource ();

Input p = new input (s);
Output o = new output (s);

thread T1 = new Thread (p);
Thread t2 = new Thread (o);

T1.start ();
T2.start ();

}
}

Java Multithreading (thread communication-waiting for a new mechanism-code optimization)

Related Article

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.