Java Fundamentals: Thread synchronization

Source: Internet
Author: User

A: First look at the program


Look at the results of the output:

Thread-0, you're the 2nd thread to use a timer.
Thread-1, you're the 2nd thread to use a timer.

The result is clearly problematic:

This is because two threads access the same timer object, where one thread calls the timer's Add method, num++, this time, another thread may also call the Add method, num + +, then thread 1 output, thread 2 output, the output is the same num = 2


II: Solutions

The Add method adds the synchronized keyword : public synchronized void Add (String name) {

Or inside the timer, execute the code block

Synchronized (this) {  num++;try {thread.sleep (1);} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN (name + ", you are the first" + num + "thread using the Timer");}

Both of these methods, the truth is one, are implemented to lock the timer object.


Java Fundamentals: Thread synchronization

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.