JAVA 24th (multithreading (III)-Thread Synchronization

Source: Internet
Author: User

JAVA 24th (multithreading (III)-Thread Synchronization


Continue selling tickets as an Example


I. Thread Security Solution

The first form of synchronization: Synchronous Code Block


Ideas:

Encapsulate the thread code of multiple operations that share data. When a thread executes the Code, other threads are not allowed to participate in the operation, the code must be executed by the current thread before other threads can participate in the operation.

Solve this problem with synchronous code blocks in java

Synchronous Code block format:

Synchronized (object)

{

Code to be synchronized

}

Class Ticket implements Runnable {private int num = 100; Object god = new Object (); // You can also customize it. We recommend that you use the existing public void run () {while (true) {synchronized (god) // synchronize {if (num> 0) {try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} System. out. println (Thread. currentThread (). getName () + ".. sale .. "+ num --) ;}}}} public class Main {public static void main (String [] args) {Ticket t = new Ticket (); thread j1 = new Thread (t); Thread j2 = new Thread (t); Thread j3 = new Thread (t); Thread j4 = new Thread (t); j1.start (); j2.start (); j3.start (); j4.start ();}}

The Object of an Object is like a lock, which monitors synchronization. When a thread is executing, other threads cannot execute

Benefits of synchronization:Solved thread security issues

Disadvantages of synchronization: When a thread sleep, the execution right is released, the execution right is assigned to other threads, and then the synchronization lock is judged to be complete and cannot be obtained, which will reduce the efficiency compared with the previous one, is within the tolerable range


Ii. Prerequisites for synchronization

If security issues still exist after synchronization, you must understand the synchronization prerequisites.

Premise: the synchronization must have multiple threads and use the same lock (one thread does not need to be synchronized, and multiple locks will lose the value of synchronization)


Iii. Second form of synchronization: Synchronous Functions


/** Requirement: * two people save money in the Bank, 10 each time, and each person saves three times. ***/class Bank {private int sum; private Object obj = new Object (); // Synchronous Code block representation/* public void add (int num) {synchronized (obj) {sum + = num; try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} System. out. println ("sum =" + sum) ;}} * // synchronous Function Format public synchronized void add (int num) {sum + = num; try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} System. out. println ("sum =" + sum) ;}} class Custom implements Runnable {private Bank bank Bank = new Bank (); public void run () {for (int I = 0; I <3; I ++) {bank. add (10) ;}} class Main {public static void main (String [] args) {Custom tCustom = new Custom (); Thread j1 = new Thread (tCustom ); thread j2 = new Thread (tCustom); j1.start (); j2.start ();}}


What is the lock for verifying the synchronous function? (Understanding)

Class Ticket implements Runnable {private int num = 100; Object god = new Object (); // You can also customize it. We recommend that you use the existing boolean flag = true; public void run () {if (flag = true) {while (true) {synchronized (this) // synchronize {if (num> 0) {try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} System. out. println (Thread. currentThread (). getName () + ".. obj .. "+ num --) ;}}} else {while (true) this. show () ;}} public synchronized void show () {if (num> 0) {try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} System. out. println (Thread. currentThread (). getName () + ".. fu .. "+ num --) ;}} class Main {public static void main (String [] args) {Ticket t = new Ticket (); Thread j1 = new Thread (t ); thread j2 = new Thread (t); j1.start (); try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} t. flag = false; j2.start ();}}


The lock used by the synchronous function is this

Differences between synchronous functions and synchronous code blocks:

The lock of the synchronous function is fixed. this means that the lock of the synchronous code block is arbitrary.

We recommend that you use the synchronized code block during synchronization.


What is the lock used to verify the static synchronization function? (Understanding)

The lock of the static synchronization function is not this, because there is no such lock

Class Ticket implements Runnable {private static int num = 100; Object god = new Object (); // You can also customize it. We recommend that you use the existing boolean flag = true; public void run () {if (flag = true) {while (true) {synchronized (this. getClass () // synchronized (Ticket. class) {if (num> 0) {try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} System. out. println (Thread. currentThread (). getName () + ".. obj .. "+ num --) ;}}} else {while (true) this. show () ;}} public static synchronized void show () {if (num> 0) {try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} System. out. println (Thread. currentThread (). getName () + ".. fu .. "+ num --) ;}} class Main {public static void main (String [] args) {Ticket t = new Ticket (); Thread j1 = new Thread (t ); thread j2 = new Thread (t); j1.start (); try {Thread. sleep (10);} catch (InterruptedException e) {// TODO: handle exception} t. flag = false; j2.start ();}}

Static synchronization function lock the bytecode file object to which the function belongs

You can use the getClass method or the current class name. 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.