Multithreading-video learning notes for bixiangdong java basic tutorial and Bi Xiangdong learning notes
Multi-thread running security issues
Example: Ticket Sales System
1 class Ticket implements Runnable 2 {3 // defines the static variable ticket 4 private static int ticket = 100; 5 public void run () 6 {7 while (true) 8 {9 // determine whether the ticket number is greater than 010 if (ticket> 0) 11 {12 try13 {14 Thread. sleep (10); 15} 16 catch (InterruptedException ie) 17 {18 System. err. println ("Error:" + ie); 19} 20 System. out. println (Thread. currentThread (). getName () + "-- sale:" + ticket --); 21} 22} 23} 24 25} 26 public class ThreadDemo27 {28 29 public static void main (String [] args) 30 {31 // create a Ticket object 32 Ticket t = new Ticket (); 33 // create four threads 34 Thread t1 = new Thread (t ); 35 Thread t2 = new Thread (t); 36 Thread t3 = new Thread (t); 37 Thread t4 = new Thread (t ); 38 // start four threads respectively 39 t1.start (); 40 t2.start (); 41 t3.start (); 42 t4.start (); 43 44} 45}
Run:
Finally, we printed out the incorrect ticket with "0,-1,-2" (the ticket number ranges from 1 to 100). The multi-thread security problem occurs.
Cause:
When multiple statements share data with one thread during operations, one thread only executes a portion of the statements, but it has not been executed yet,
Another data is involved in the execution, resulting in data sharing errors.
Solution:
Statements that share data for multiple operations can only be executed by one thread. Other threads are not allowed to participate in the execution process.
Java provides a professional solution for multi-threaded synchronization, that is, to synchronize code blocks.
Multithread Synchronous Code Block
Synchronized (object)
{Code block to be synchronized}
The object is like a lock. The lock-holding thread can be executed in the synchronization code block,
The thread that does not hold the lock cannot even obtain the execution right of the CPU, because the lock is not obtained.
Example: the bathroom on the train.
Prerequisites for synchronization:
1. There must be two or more threads.
2. Multiple Threads must use the same lock.
Benefit: it solves the security problem of multithreading.
Disadvantage: the lock needs to be determined, which consumes more resources.
Generally, you cannot place the run () method in the synchronization code block. Otherwise, it is a single thread.
Synchronization method:
Bank
There are two depositors, respectively saving 300 yuan, each saving 100 yuan, saving 3 times
Objective: Is there a security issue in this thread? If so, how can this problem be solved?
How to find the problem:
1. Identify the code that is run in multiple threads
2. clearly share data
3. Identify the code operations in multi-threaded code to share data.
1 class Bank 2 {3 // defines sum, which indicates the total amount of the Bank 4 private int sum; 5 Object obj = new Object (); 6 public void add (int n) 7 {8 9 // sum is the shared data, and there are two operations on sum. 10 // to prevent security issues, use Synchronous Code Block 11 synchronized (obj) 12 {13 sum = sum + n; 14 try15 {16 Thread. sleep (10); 17} 18 catch (InterruptedException ie) 19 {20 System. err. println ("Error:" + ie); 21} 22 System. out. println ("sum =" + sum); 23} 24} 25} 26 class Cus implements Runnable27 {28 private Bank B = new Bank (); 29 // save three times 30 public void run () 31 {32 for (int I = 0; I <3; I ++) 33 B. add (100); 34} 35} 36 public class BankDemo37 {38 public static void main (String [] args) 39 {40 Cus cus = new Cus (); 41 // create two threads, representing the Deposit Process of two depositors 42 Thread t1 = new Thread (cus); 43 Thread t2 = new Thread (cus); 44 t1.start (); 45 t2.start (); 46} 47}
Note: two manifestations of synchronization: a. synchronous code block B. synchronous Function
The lock of the synchronization method is this
Which lock is used for synchronization?
If a method needs to be called by an object, the method has a reference to the object, that is, this.
So the lock of the synchronization method is this.
The lock of the static synchronization method is a Class object.
When the synchronization method is modified statically, the lock used is not this, because this cannot be used in the static method.
When a static method is imported into the memory, the memory does not have the object of this class, but there must be a bytecode file object corresponding to this class.
Class Name. class. The object type is Class.
Static synchronization method. The lock used is the bytecode file object of the class of the method. Class Name. class
Singleton Design Mode
1. Hungry Chinese Style
1 class Single2 {3 private static final Single s=new Single();4 private Single(){}5 public static Single getInstance()6 {7 return s;8 }9 }
2. Lazy style:
1/* 2 test site during the interview: 3 4 lazy features: instance loading delay 5 problems: security problems occur during multi-thread access 6 solutions: you can use the synchronous method or synchronous code block. 7, but it is inefficient. You can use dual-judgment to reduce the number of locks to be judged and slightly improve efficiency. 8. Synchronization: the lock used is the bytecode object of the class 9 10 */11 class Single12 {13 private static Single s = null; 14 private Single () {} 15 public static Single getInstance () 16 {17 // Through Double judgment, reduce the number of lock judgment times and slightly improve efficiency. 18 if (s = null) 19 {20 synchronized (Single. class) 21 {22 if (s = null) 23 s = new Single (); 24} 25} 26 return s; 27} 28}
Deadlock: Nested synchronization in synchronization
Deadlock example
1 class Test implements Runnable 2 { 3 private boolean flag; 4 Test(boolean _flag) 5 { 6 flag=_flag; 7 } 8 public void run() 9 {10 if(flag)11 {12 synchronized(MyLock.locka)13 {14 System.out.println("if locka");15 synchronized(MyLock.lockb)16 {17 System.out.println("if lockb");18 19 }20 21 }22 23 }24 else25 {26 synchronized(MyLock.lockb)27 {28 System.out.println("else lockb");29 synchronized(MyLock.locka)30 {31 System.out.println("else locka");32 33 }34 35 }36 37 }38 39 }40 }41 class MyLock42 {43 static Object locka=new Object();44 static Object lockb=new Object();45 }46 public class DeadLockTest47 {48 public static void main(String[] args)49 {50 Thread t1=new Thread(new Test(true));51 Thread t2=new Thread(new Test(false));52 t1.start();53 t2.start();54 55 }56 57 }