Prerequisites for synchronization
- Must have two or more threads
- Must be all threads using the same lock
This ensures that only one of the threads in the synchronization is running
Note When multithreading security issues are set to sync
- Identify which code is multithreaded to run code
- Identify what is shared data
- Define which statements in a multithreaded run code are operations that share data
Advantages of synchronization
Resolves a multi-threaded security issue
Disadvantages of synchronization
Multiple threads to determine lock, more resource-intensive
class ThreadDemo1 { Public Static voidMain (string[] args) {Ticket tic =NewTicket (); Thread T1 =NewThread (TIC); Thread t2 =NewThread (TIC); Thread t3 =NewThread (TIC); T1.start (); T2.start (); T3.start (); }} class Ticket implements Runnable { Private intTicket = -; Object obj =NewObject (); Public voidRun () { while(true) {synchronized (obj) {if( This. Ticket >0) {Try{Thread.Sleep (Ten); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +" ... "+ This. ticket); This. ticket--; } } } }}
Class ThreadDemo2 { Public Static void Main(string[] args) {Customer cus =NewCustomer (); Thread T1 =NewThread (cus); Thread t2 =NewThread (cus); T1.start (); T2.start (); }}/** * A bank, there are two customers to the bank to save money, each customer has 300 yuan, each time is saved 100 yuan, each person saves 3 times * * /Class bank{Private intSummoney; Public synchronized void Add(intMoney) { This. Summoney = This. Summoney + Money;Try{Thread.Sleep (Ten); }Catch(Interruptedexception e) {E.printstacktrace (); } System.out.println ("Summoney ="+ This. Summoney); }}class Customer implements runnable{PrivateBank Bank =NewBank (); Public void Run(){ for(inti =1; i<=3; i++) {Bank.add ( -); } }}
Java Multithreading--the premise of synchronization