There are two ways of/** synchronization:One, synchronous code block, two, synchronous functionUse synchronized note that if you synchronize the code that needs to be synchronized, you don't need to find the problem:1, clear which code is multithreaded running code2. Clear sharing of data3. Clear which statements in multithreaded run code are operations sharing data. **/class bank{private int sum;Object obj = new Object ();Public synchronized void Add (int n)//This is the synchronization function, which simplifies the code{Synchronized (obj)//{sum = sum + N;Try{thread.sleep (10);} catch (Exception e) {}System.out.println ("total:" +sum);//}}}class Cus implements runnable{Private Bank B = new Bank ();public void Run (){for (int x=0; x<3; x + +){B.add (100);}}}class threadbank{public static void Main (string[] args){Cus C = new Cus ();thread T1 = new Thread (c);Thread t2 = new Thread (c);T1.start ();T2.start ();}}
Multi-Threaded---synchronization function (reprint)