Multi-Threaded---synchronization function (reprint)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.