Multithreading (ii) life cycle and synchronization

Source: Internet
Author: User
Tags sleep static class thread thread class

continue to learn from the above.


Four: The life cycle of a thread:

As can be seen from the figure above, a thread is divided into five stages from birth to death:

1). Create Status

• When a new thread object is created with the newly operator, the thread is in the created state.

• The thread in the created state is just an empty thread object and the system does not allocate resources for it

2). Operational status

• The start () method of the execution thread assigns the required system resources to the thread, schedules it to run, and invokes the thread body-run () method, which causes the thread to be in a running (Runnable) state.

• This state is not in the running state (Running) because the thread may not actually run.

3). Non-operational status

. When the following event occurs, the running thread is moved to a non-operational state.

Called The Sleep () method;

• The thread calls the wait method to wait for a specific condition to be satisfied

• Thread input/output blocking

4) Return to operational status:

• A thread in sleep after a specified time has elapsed

• If the thread is waiting for a condition, the other object must notify the waiting thread condition through the Notify () or Notifyall () method

• Wait for input/output to complete if thread is blocked by input/output

5). Extinction Status

When the thread's Run method finishes executing, the thread dies naturally.



Attention:

1. How to stop a thread: You cannot use the thread class's Stop method to terminate the execution of a thread. In general, to set a variable, in the Run method is a loop, each time the loop checks the variable, if the condition is satisfied to continue to execute, or jump out of the loop, the thread ends.

2. You cannot rely on thread precedence to determine the order in which threads are executed.


V: Multithreading concurrency

Multithreading concurrency is a common phenomenon in thread synchronization, and Java multithreading provides the synchronized keyword to avoid multi-threaded concurrency to solve multi-threaded shared data synchronization problems.

Synchronized keyword: When the synchronized keyword modifies a method, the method is called a synchronous method.

Each object in the 1.Java has a lock (lock) or monitor, and when the synchronized method of an object is accessed, it means that the object is locked, and no other thread can access the Synchronized method again. Until the previous thread executes the method (or throws an exception), the object's lock is freed and other threads are likely to access the Synchronized method again.

2. If an object has more than one synchronized method and a thread has entered a synchronized method at some point, the other thread is unable to access any of the synchronized methods of the object until the method has finished executing.

3. If a synchronized method is static, then when the thread accesses the method, it locks not the object that the Synchronized method resides in, but the class object that corresponds to the object that the synchronized method is in. Because no matter how many objects a class has in Java, these objects correspond to a unique class object, so when a thread accesses two static,synchronized methods of two objects of the same class individually, their order of execution is also sequential, that is, a thread first executes the method, After execution, another thread starts executing.

4. Synchronized block, notation:

Synchronized (object) 

{ 



Indicates that the thread will lock the object when executing.

The 5.synchronized method is a coarse-grained concurrency control in which only one thread can execute the synchronized method at a time, and the synchronized block is a fine-grained concurrency control that synchronizes code in the block, within the method, Code outside the synchronized block can be accessed concurrently by multiple threads.

Thread state diagram for synchronization:



Code implementation

public static void Main (string[] args) {new traditionalthreadsynchronized (). Init ();/} private void Init () { Final Outputer outputer = new Outputer ();//New Thread (new Runnable () {@Override public void run () {while (true)
					{try {thread.sleep (10);
					} catch (Interruptedexception e) {e.printstacktrace ();

		} outputer.output ("1");//}}}). Start ();
					New Thread (New Runnable () {@Override public void run () {while (true) {try {thread.sleep (10);
					} catch (Interruptedexception e) {e.printstacktrace ();
				} outputer.output3 ("2");
	}}). Start ();
			} static class Outputer {public void output (String name) {int len = name.length ();

				Synchronized (Outputer.class) {for (int i = 0; i < len; i++) {System.out.println (Name.charat (i));
			} System.out.println (); }} public synchronized void Output2 (String name) {int len = Name.leNgth ();

				Synchronized (this) {for (int i = 0; i < len; i++) {System.out.println (Name.charat (i));
			} System.out.println ();
			

				}} public static synchronized void Output3 (String name) {int len = name.length ();

				for (int i = 0; i < len; i++) {System.out.println (Name.charat (i));
			} System.out.println (); }

		
	}



Synchronized is a synchronization mechanism built into the Java language level. The mechanism behind synchronized is the locking mechanism of Java at the language level:


Class Lock: For each class, a class lock is automatically installed, which is a 1 instance lock: For each class instantiation of an object, automatically matching an object lock, the lock critical volume of 1

For a class lock, it is now noted that only one method can be applied to a class: Static method Lock: synchronized ();

For instance locks, there are several ways to do this: non-static method Lock: Synchronized methods (); Code block Lock: synchronized{} or synchronized (this) {} Specifies class instance lock: Synchronized (Object ob) {}


The non-static method lock is the same as the code block lock, which is a lock on the instance of the current owning class. It is interesting to specify class instance lock, which is to lock the object OB in parentheses, which can be used to construct a slightly responsible parallel program model with the use of the specified class lock.

Where class locks and instance locks are independent, do not conflict with each other, a synchronized specifies a lock, either a class lock or an instance lock, which is mutually exclusive.

In multi-threading, it is still a reference to the Japanese author of the "Java Multithreaded design pattern" in the example:

Issue: [Java] view Plaincopy public class Something () {public synchronized void Issynca () {} publ  IC synchronized void Issyncb () {} public static synchronized void Csynca () {} public static synchronized void Csyncb () {}}

So, for the two instances A and b of the something class, how can the following group of methods be accessed by more than 1 threads at the same time? X.issynca () and X.ISSYNCB () X.issynca () and Y.issynca () X.csynca () and Y.CSYNCB () X.issynca () and Something.csynca ()

: Both synchronized domain access to the same instance and therefore cannot be accessed concurrently for different instances, so it can be accessed at the same time because it is static synchronized, so the different instances will still be limited, equivalent to Something.issynca () with SOMETHING.ISSYNCB (), so it cannot be accessed concurrently. Able to access at the same time, because one is an instance lock and one is a class lock.

Summarize

Synchronized language level lock mechanism, so that concurrent projects, without adding lock control class, the direct itself the original ecological support, very convenient, but note that the synchronized lock only two granularity, one is class lock, one is an instance lock, and the critical zone mutex is 1, For some need critical area greater than 1, lock granularity greater, dynamic control, that synchronized is not enough. Need to have a special signal quantity and other mechanisms.

The last point is that synchronized keyword can not be directly inherited, subclass in the inheritance is responsible, overwrite the parent class synchronized method, must also display with synchronized keyword. The synchronized field of the parent class is still valid in the subclass object if the subclass does not overwrite the non-static method of the parent class synchronized keyword and directly inherits and uses the non-static method of the parent class.

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.