com.ruizhukai.demo01 Package; / * * * t1 and t2 * * Asynchronous model becomes: t1, t2 t1 thread of execution, a thread of execution, etc. No one who is between the two threads t2 * synchronous programming model: Thread t1 and t2 when the thread execution thread must wait t1 t2 end of thread execution, t1 threads to execute, which is synchronous programming model * * * when you want to synchronize it? Why introduce thread synchronization it? * 1. In order to secure the data, despite lower utilization of the application, but in order to ensure that data is secure, must join the thread synchronization mechanism * * 2. Under what conditions to use thread synchronization * First, it must be multi-threaded environment * second, a multithreaded environment to share the same data * third, related to the shared data modification operation * * * the following example program illustrates withdrawal * * / public class TestThread5 { public static void main (String [] args) { the Account a = new Account("actno-001" ,500.0); Prooessoes p = new Prooessoes(a); Thread t1 = new Thread(p); Thread t2 = new Thread(p); t1.start(); t2.start(); } } //取款线程 class Prooessoes implements Runnable{ //账户 Account act; //Constructor Prooessoes (Account act){ this.act = act; } @Override public void run() { act.withdraw(100.0); System.out.println("取款成功" + act.getBalance()); } } //账户 class Account{ private String actno;//账户 private double balance;//余额 public Account(){} public Account(String actno,double balance){ this.actno = actno; this.balance = balance; } public void setActno (String actno) { the this .actno = actno; } public void the setBalance ( Double Balance) { the this .balance = Balance; } public Double the getBalance () { return Balance; } public String getActno () { return actno; } @ a method of withdrawal of external public void the withdraw ( Double Money) { // the current account to make a withdrawal // the code to be synchronized, the synchronization statement block into / * Principle: t1 and t2 thread thread t1 thread execution to here, met the synchronized keyword, it will go to lock this object if this object is to find the lock, then enter the synchronized statement blocks execution of the program, when substitute statement block Code after the execution, the thread t1 return this object lock in sync block of statements in the thread t1, t2 if the thread also came execute the following code, also encountered the synchronized keyword , so it went to lock this object, but the object lock t1 thread is held only waiting for this return of this object * / the synchronized ( this ) { Double the After = Balance - money; // remaining money = amount before withdrawal - withdrawal amount // delay, so that the thread sort order the try { the Thread.sleep ( 1000 ); } the catch (Exception E) { } //更新 this.setBalance(after); } } }