Thread Issue 3 (Synchronized,wait,notify,notifyall, class lock, Object Lock)

Source: Internet
Author: User

/**
* Knowledge One:
* Implement threading, there are two methods, one is to inherit the thread class, one is to implement the Runnable interface.
* This article recommends the implementation of the Runnable interface method.
* 1. Put the data that needs to be shared (can be static, non-static variables) in an implementation runnable
* Interface class, and then pass the instance of this class to multiple thread construction methods. This way, the newly created
* Multiple thread, all together have a runnable instance, share the same data.
* 2. If you adopt a method that inherits the thread class, you will have to use static statically members.
* If you share more data, you need a large number of static members, so that the program data structure confusion,
* Difficult to expand. This situation should be avoided as much as possible.
*
* Knowledge II:
* Java process synchronization is achieved through synchronized (), it should be explained that
* The Java synchronized () method is similar to the mutex memory block in the operating system concept, in the type of object in Java,
* All with a memory lock, after the thread gets the memory lock, other threads can not access the memory, in order to achieve simple synchronization in Java, mutex operation.
* Understand this principle to understand why synchronized (this) differs from synchronized (static XXX),
* Synchronized is to request memory lock for memory block, this keyword represents an object of class.
* So its memory lock is a mutex for the same object, and the static member belongs to the class, and its memory space is common to all members of that class.
* This causes synchronized () to lock the static member, which is equivalent to lock the class, that is, to implement mutual exclusion among all members of the class.
* Only one thread at a time can access instances of this class. If you simply want to implement a thread mutex in Java, it's enough to understand that.
* But if you need to wake up between threads, you need to use object.wait (), object.nofity ().
*
* Obj.wait (), and obj.notify () must be used with synchronized (OBJ), that is, wait,
* and notify is for the obj lock has been acquired to operate, from a grammatical point of view is
* Obj.wait (), obj.notify must be in synchronized (OBJ) {...} Within the statement block.
* Functionally, wait means that the thread is actively releasing the object lock after acquiring the object lock, while this thread sleeps.
* Until the thread is awakened by another thread calling the object's notify () to continue to acquire the object lock and continue execution.
* the corresponding notify () is the wake-up operation of the object lock. But one thing to note is that after the Notify () call,
* Does not release the object lock immediately, but after the corresponding synchronized () {} statement block execution end, automatically release the lock,
* The JVM randomly selects a thread in the Wait () object lock, assigns its object lock, wakes the thread, and continues execution.
* This provides synchronization, wake-up operations between threads. Both Thread.Sleep () and object.wait () can pause the current thread,
* Release CPU control, the main difference is that object.wait () releases the control of the object lock while releasing the CPU.
*
Note
* 1) must be inside the synchronized to use the Notify,notifyall,wait method;
* 2) Synchronized must be an object or a class as a lock resource, once a thread enters this sychronized section,
* Then synchronized (this lock resource) all the code places other threads are not allowed to enter.
*
* Knowledge Three:
* 1, the scope of the SYNCHRONIZED keyword has two kinds:
* 1) is within an object instance, synchronized Amethod () {} can prevent multiple threads from accessing the object at the same time synchronized method
* (If an object has multiple synchronized methods, as long as one thread accesses one of the synchronized methods, the other threads do not
* Can access any one of the synchronized methods in this object at the same time. At this point, the synchronized method of the different object instances is not interfering.
* In other words, other threads can access the Synchronized method in another object instance of the same class at the same time;
* 2) is the scope of a class, synchronized static astaticmethod{} prevents multiple threads from accessing the synchronized static method in this class at the same time.
* It can work on all object instances of the class.
* 2, in addition to the method before using the Synchronized keyword, the synchronized keyword can also be used in a block in the method, indicating that only the resources of this block to implement mutually exclusive access.
* Usage is: synchronized (this) {chunk}, which is scoped to the current object;
* 3, synchronized keyword is not inherited, that is, the method of the base class synchronized F () {} in the inheriting class is not automatically synchronized F () {},
* instead it becomes f () {}. Inheriting a class requires that you explicitly specify one of its methods as the Synchronized method;
*/

public class Queuethreadwaitnotify implements Runnable {

Private Final Object lock = new Object ();

public static void Main (string[] args) throws Interruptedexception {

Queuethreadwaitnotify a = new queuethreadwaitnotify ();

Many threads are blocked because they want to access a lock object.
Queued, waiting for the resource to be released.

for (int i = 1; I <=16; i++) {
New Thread (A, string.valueof (i)). Start ();
}
Hibernate the main main thread for some time first
Thread.Sleep (5000);

Turns on wake on the blocking queue.
New Thread (A, "WakeUp"). Start ();

}


public void Run () {
String name = Thread.CurrentThread (). GetName ();


if (Name.equals ("WakeUp")) {
System.out.println ("WakeUp get object before---" + name);
Synchronized (lock) {
System.out.println ("WakeUp get object after---" + name);
System.out.println ("WakeUp Get Object" + name);

/**
* The difference between notifyall () and notify ():
* Notifyall is to notify multiple blocking threads
* Notify is to notify a blocking thread
* Notifyall () method of use:
*/
Lock.notifyall ();

/**
* How to use notify:
* If the above Notifyall code is commented,
* Using the following notify will cause only one thread to wake up, and the other blocked threads are still blocking.
*/
Lock.notify ();

System.out.println ("WakeUp Give up Object" + name);
}


} else {
System.out.println ("Give up object before---" + name);
Synchronized (lock) {
System.out.println ("Give up object after---" + name);
try {
SYSTEM.OUT.PRINTLN (name + "Give up object---" + name);
Lock.wait ();
SYSTEM.OUT.PRINTLN (name + "Get lock object again---" + name);

/**
* How to use notify:
* This sentence must be added to prevent other threads from being blocked when using notify () above.
*/
Lock.notify ();
} catch (Interruptedexception e) {


E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN (name + "Get lock object end.") ---"+ name");
}
}
}
}

Thread Issue 3 (Synchronized,wait,notify,notifyall, class lock, Object Lock)

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.