Learn Java multithreading with examples-2

Source: Internet
Author: User

In the previous article, we use an example to illustrate why concurrent programming should be synchronized, and let's consolidate it.

If the object has variable state variables and is accessed by multithreading, then we need to do atomic manipulation of the state change of mutable state variables.

The lock mechanism is an efficient way to ensure that the state of a variable is in an atomic operation when it is updated.

Java provides a built-in locking mechanism to support atomicity: synchronous blocks of code (Synchronized block).

The synchronization code block consists of two parts: one is an object reference as a lock, and one is a block of code protected by this lock.

Let's recall the last question in the previous article:

1: We can see the above example of the synchronized is added to the method, then we can also how to write it?

The synchronized that is added to the method lock is the synchronization code block of the whole method body, the synchronization code block has, what is the lock object? Let's take a look at this piece of code:

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class Safethread {int id = 0; @safe public <span style= "Color: #ff0000;" >synchronized </span>int getId () {   <span style= "color: #ff0000;" >return ++id;//Lock code block </span>}}</span>

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class ThreadStart {public static void main (string[] para) {& Lt;/span>

<span style= "FONT-SIZE:18PX;" ><span style= "color: #ff0000;" >//here safe is the lock object, it is </span><span style= "color: #ff0000;" Reference to an instance of >safethread () </span>safethread safe = new Safethread (); for (int i=0;i<10;i++) {ThreadRead1 T1 = new ThreadRead1 (SAFE); ThreadRead2 t2 = new ThreadRead2 (safe); T1.start (); T2.start ();}} </span>

We figure out, lock the object and lock the code block, that can be thought out, lock code block can be written in many ways, as long as we get the lock object, then regardless of the lock code block is how to write can achieve multi-threaded synchronization.

Let's look at some of the following:

Notation 1:

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class Safethread {int id = 0; @safepublic  int getId () {sy Nchronized (safethread.class) {return ++id;}}} </span>

Notation 2

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class Safethread {int id = 0;object Sync = new Object (); @sa Fepublic  int getId () {synchronized (sync) {return ++id;}}} </span>

Notation 3:

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class Safethread {static int id = 0; @safepublic static sync hronized int getId () {return ++id;}} </span>

Methods that use static to decorate are default to the class object as the lock.


2:synchronized is the object or code or method locked?

By analyzing the above questions, I can imagine what we are locked up with.

Answer: It should be the object.

Let's use examples to illustrate everything!

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class Safethread {static int id = 0; @safepublic static sync hronized int getId () {return ++id;} Public  synchronized void Testprint () {System.out.println ("Enter Testprint Method!"); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Exit Testprint Method!");}} </span>

The Testprint method has been added to the synchronized, let's call this method with multi-line access.

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class ThreadStart {public static void main (string[] para) {f or (int i=0;i<10;i++) {ThreadRead1 T1 = new ThreadRead1 (); T1.start ();}}} </span>
<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu * */public class ThreadRead1 extends thread{safethread safe = null;public ThreadRead1 () {}public ThreadRead1 (Safethread o) {safe = O;} public void Run () {        safe = new Safethread (); Safe.testprint ();}} </span>


Look at the results:

<span style= "FONT-SIZE:18PX;" >enter Testprint Method! Enter Testprint Method! Enter Testprint Method! Enter Testprint Method! Enter Testprint Method! Enter Testprint Method! Enter Testprint Method! Enter Testprint Method! Enter Testprint Method! Enter Testprint Method! Exit Testprint Method! Exit Testprint Method! Exit Testprint Method! Exit Testprint Method! Exit Testprint Method! Exit Testprint Method! Exit Testprint Method! Exit Testprint Method! Exit Testprint Method! Exit Testprint Method!</span>

This result has some meaning, we have added synchronized to the method, why does it not work?

The reason is very simple, we look at the thread ThreadRead1 implementation code, Safethread object is created online Cheng, that is to say 10 threads is created 10 safethread instances, so even synchronized locked block of code does not work.

Let's Change the code:

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class ThreadStart {public static void main (string[] para) {& Lt;span style= "color: #ff0000;" >safethread safe = new Safethread (); </span>for (int i=0;i<10;i++) {ThreadRead1 T1 = new <span style= "color: #ff6666; " >threadread1 (SAFE) </span>;t1.start ();}} </span>
<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu * */public class ThreadRead1 extends thread{safethread safe = null;public ThreadRead1 () {}public ThreadRead1 (Safethread o) {safe = O;} public void Run () {safe.testprint ();}} </span>

Let's look at the results of the operation:

<span style= "FONT-SIZE:18PX;" >enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method! Enter Testprint Method! Exit Testprint Method!</span>


The result is what we want, why is this synchronized the steward? We see the red part of the main method in the ThreadStart class, we create an instance of Safethread and its reference before starting the thread, and use its reference as a parameter to initialize the thread class ThreadRead1, That's when the reference to the Safethread instance is a sweet Bobo, who gets who can lock the synchronized locked block of code and execute the block code.

Here's an example of what you can do with your own practice and see what the results are.

Example:

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class ThreadStart {public static void main (string[] para) {f or (int i=0;i<3;i++) {ThreadRead1 T1 = new ThreadRead1 (); T1.start ();}}} </span>


<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu * */public class ThreadRead1 extends thread{safethread safe = null;public ThreadRead1 () {}public ThreadRead1 (Safethread o) {safe = O;} public void Run () {safe = new Safethread (); Safe.testprint ();}} </span>

The two implementations of the called Class are as follows:

Implementation 1:

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class Safethread {static int id = 0; @safepublic static sync hronized int getId () {return ++id;} Public   void Testprint () {<span style= "color: #ff0000;" >synchronized (Safethread.class) </span>{system.out.println ("Enter Testprint Method!"); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Exit Testprint Method!");}}} </span>

Implementation 2:

<span style= "FONT-SIZE:18PX;" >package com.home.thread;/** * @author Gaoxu *  */public class Safethread {static int id = 0; @safepublic static sync hronized int getId () {return ++id;} Public <span style= "color: #ff0000;" >static synchronized </span>  void Testprint () {System.out.println ("Enter Testprint Method!"); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Exit Testprint Method!");}} </span>

This example also makes it very clear that synchronized locks the object, not the code, and you will understand it more deeply as you run it.

Today, following the example of Java multithreading is here, let us consider the following two questions.

1: What is the difference between the different synchronized, and how do you write the code that creates the thread?

2: How the deadlock, the active question all produces.












Learn Java multithreading with examples-2

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.