Continue to sell tickets for example
One, the solution of thread safety problem
The first manifestation of synchronization: Synchronizing code blocks
Ideas:
Encapsulates the thread code that has multiple operations sharing data, and when the thread executes the code, the other threads are not allowed to participate in the operation, and the other threads must be able to participate in the operation once the thread has finished executing the code.
Solve this problem in Java with a synchronized block of code
Synchronous code block Format:
Synchronized (object)
{
Parts of code that need to be synchronized
}
Class Ticket implements runnable{private int num = 100;object god = new Object ();//can also be customized, it is recommended to use the existing public void run () {while (t Rue) {synchronized (God)//sync {if (num>0) {try {thread.sleep];} 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 ();}}
object is like a lock, monitoring the synchronization, when the thread is executing, other threads cannot execute
Benefits of synchronization: resolves thread security issues
The disadvantage of synchronization: When a thread sleep, the release of execution, execution will give other threads, and then to determine the synchronization lock, judgment and not go, so the relative previously will reduce efficiency, is within the tolerable range
Second, the premise of synchronization
If there is a security problem after synchronization, you must understand the prerequisites for synchronization
Premise: There must be multiple threads in the synchronization and use the same lock (one thread does not need to synchronize, multiple locks lose the value of synchronization)
Third, the second manifestation of synchronization: Synchronization function
*/* Demand: * Two people to the bank to save money, each time deposit 10, everyone is three times * * */class bank{private int sum;private Object obj = new object ();//Synchronous code block representation/*pu Blic void Add (int num) {synchronized (obj) {sum + = num;try {Thread.Sleep];} catch (Interruptedexception e) {//Todo:handl E exception}system.out.println ("sum =" +sum);}} *///synchronous function representation public synchronized void Add (int num) {sum + = num;try {Thread.Sleep (Ten)} catch (Interruptedexception e) {//To Do:handle exception}system.out.println ("sum =" +sum);}} Class Custom implements Runnable{private Bank Bank = new Bank ();p ublic 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 that verifies the synchronization function? Know
Class Ticket implements runnable{private int num = 100;object god = new Object ();//can also be customized, it is recommended to use the existing Boolean flag = True;publi c void Run () {if (flag==true) {while (true) {synchronized (this)//Synchronize {if (num>0) {try {thread.sleep];} 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 ()} catch (Interruptedexception e) {//Todo:handle Exce Ption}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;} catch (Interruptedexception e) {//Todo:handle Exception}t.flag = False;j2.start (); }}
The lock used by the synchronization function is this
The difference between a synchronization function and a synchronous code block:
The lock of the synchronization function is fixed this, the lock of the synchronous code block is arbitrary
Therefore, it is recommended to use a synchronous code block when synchronizing
What is the lock that verifies the static synchronization function? Know
The lock for the static sync function is not this, because there is no this
Class Ticket implements runnable{private static int num = 100;object god = new Object ();//can also be customized, it is recommended to use the existing Boolean flag = Tru e;public void Run () {if (flag==true) {while (true) {synchronized (This.getclass ()))//synchronized (Ticket.class) {if (num >0) {try {thread.sleep ()} 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];} catch (Interruptedexception e) {//Todo:hand Le 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;} catch (Interruptedexception e) {//Todo:handle Exception}t.flag = False;j2.start (); }}
The lock of a static synchronization function the byte-code file object that the function belongs to
You can use the GetClass method or use the current class name. class to get
Java Learning Lesson 24th (Multithreading (iii))-thread synchronization