Thread advanced Application-Experience 2-synchronous lock explanation and face test case analysis

Source: Internet
Author: User
Tags static class

1. Introduction of Synchronous lock

2. Synchronous Lock Case Analysis

Package com.itcast.family; public class Traditionalthreadsynchronized {public static void main (string[] args) {new traditionalthreadsynchronize

	D (). Init (); The function of the method is that the static method of the external class cannot instantiate the inner class object, so it cannot be instantiated directly in main of the outer class, the common method to create an intermediary private void init () {final Outputer outputer = new O
		Utputer (); Thread 1 new Thread (new Runnable () {@Override public void run () {while (true) {try {thread.sleep (
					10);
					catch (Interruptedexception e) {e.printstacktrace ();
				} outputer.output ("Yangkai");
		}}). Start (); Thread 2 new Thread (new Runnable () {@Override public void run () {while (true) {try {Thread.sle
					EP (10);
					catch (Interruptedexception e) {e.printstacktrace ();
				} outputer.output3 ("123456");
	}}). Start ();
		Static class Outputer {//The first way to use a lock: part of the code block locks String xxx = "";
 The public void output (String name) {/*synchronized () lock can be any empty string, the result is synchronized but there should be other problems, execution results: * Yangkai      			123456 123456 Yangkai 123456 can also be the parameter that the method passes in, for example, where name can be executed, but the result is problematic; execution Result: Y1a2n3g4k5a6 I Yangkai 123456 So it is generally used to represent the class itself, the method itself; The object with the lock line Chengri will be the same object, otherwise there would be an error; for example, the home code uses the same Outputer object Outputer Outputer change to New outputer will make an error because it is two Outputer objects/synchronized (Outputer.class) {for (int i = 0; i < name.length () ;
			i++) {//read a character System.out.print (Name.charat (i)) within a string;
			} System.out.println (); 
		 }//The second way to use a lock: The entire method is locked//generally only one lock is used in a class, there's a lock on the outside, or there's going to be a deadlock. * The lock in the output () method of the above two threads, one with the lock in the Output2 () method, * This can also be mutually exclusive, to achieve the requirements of synchronization, because they are using the same door bolt, that is, the same object; * are Outputer objects, a This one is directly the method in its object/public synchronized void Output2 (
		String name {for (int i = 0; i < name.length (); i++) {//read a character System.out.print (Name.charat (i)) of one of the strings;
		} System.out.println (); //3. The third method of static locking, at this point the internal class is also static/* If you use the first or the second lock directly, it will not form a mutex with the third, because the static method and the normal method of the object is not a, * then only need to change the first lock in the This parameter to Outputer. Class can be * * * PublIC static synchronized void Output3 (string name) {for (int i = 0; i < name.length (); i++) {//read a character within a string
			System.out.print (Name.charat (i));
		} System.out.println (); }/* * If you do not use the lock synchronized, the following conditions will occur: * Yangkai 123456 Yangkai 1y2a3n4g5k6 AI/} 3. Analysis of synchronous lock-face test questions Packag

e com.itcast.family; /** * Interview questions: * Child thread Loop 10 times, then the main thread loop 100 times, and then back to the child thread loop 10 times, * then back to the main thread and then cycle 100 times, so cycle 50 times, the code is as follows: * * thinking: * Writing a business class, is to not get yourself into , which embodies the high clustering characteristics of the code and the robustness of the code, * the common data (such as the synchronous lock here) or the common algorithm can be mentioned in the same class to write/public class Traditionalthreadcommunication {public
		static void Main (string[] args) {final Business Business = new Business ();
				New Thread (New Runnable () {@Override public void run () {for (int i=1;i<=50;i++) {business.sub (i);
		
		}}). Start ();
	for (int i=1;i<=50;i++) {business.main (i);
	Write a child method (to invoke the child thread) and the main method (invoke the main thread) of the business class business{private Boolean bshouldsub = true; Public synchronized void sub (int i) {while!bShouldsub) {try {////If it's not your turn to wait for a while this.wait ();
			catch (Interruptedexception e) {e.printstacktrace ();
		for (int j=1;j<=10;j++) {System.out.println ("Sub thread sequence of" + j + ", loop of" + i);
		} bshouldsub = false;
	Wakes up the next waiting thread this.notify (); The public synchronized void main (int i) {/* is better to use while, but like the effect of if, only the former code is more robust, while it prevents the thread from waking itself, which is usually called pseudo wake; * is the equivalent of a
			People dream is not to be awakened by others but their own nightmares suddenly awakened; * Then use while to prevent this from happening */while (bshouldsub) {try {this.wait ();
			catch (Interruptedexception e) {e.printstacktrace ();
		for (int j=1;j<=100;j++) {System.out.println ("main thread sequence of" + j + ", loop of" + i);
		} bshouldsub = true;
	This.notify ();
 }
}


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.