Java Threading Mechanism (iv) synchronization methods and synchronization blocks

Source: Internet
Author: User
Tags generator variables thread volatile

On the basis of previous examples, we add new functionality: Displays the player's score according to the correct and incorrect response.

public class Scorelabel extends JLabel implements Characterlistener {private volatile int score = 0;
    private int char2type =-1;
    
    Private Charactersource generator = null, typist = NULL;
        Public Scorelabel (Charactersource generator, Charactersource typist) {this.generator = generator;
        This.typist = typist;
        if (generator!= null) {Generator.addcharacterlistener (this);
        } if (typist!= null) {Typist.addcharacterlistener (this);
    Public Scorelabel () {This (null, NULL);
            Public synchronized void Resetgenerator (Charactersource newcharactor) {if (generator!= null) {
        Generator.removecharacterlistener (this);
        } generator = Newcharactor;
        if (generator!= null) {Generator.addcharacterlistener (this); } public synchronized void Resettypist (Charactersource newtypist) {if typist!= null) {Typist.removecharacterlistener (this);
        typist = Newtypist;
        } if (typist!= null) {Typist.addcharacterlistener (this);
        } public synchronized void Resetscore () {score = 0;
        Char2type =-1;
    SetScore (); Private synchronized void SetScore () {Swingutilities.invokelater (new Runnable () {@Ov
            Erride public void Run () {SetText (integer.tostring (score));
    }
        });
            @Override public synchronized void Newcharacter (characterevent CE) {if (Ce.source = = Generator) {
                if (Char2type!=-1) {score--;
            SetScore ();
        } char2type = Ce.character;
            else {if (Char2type!= ce.character) {score--;
                else {score++;
            Char2type =-1;
       }     SetScore (); }
    }
}

Here we synchronize the Newcharacter () method with synchronized because the method is invoked by multiple threads, and we simply don't know which thread will call the method at any time. This is race condition.
The volatile of the variable cannot solve the multithreading scheduling problem above, because the problem here is the problem of method scheduling, and even more frightening is the fact that there are many variables that need to be shared, some of which are judged as conditions, which causes some threads to start up before these conditional variables are set correctly.

This is not simply a matter of setting these variables to volatile, because even if these variables are not in the right state, other threads can still start.

There are several methods of synchronization that need to be noticed: Resetscore (), Resetgenerator (), and Resettypist () are called when they are restarted, as if we don't need to sync them. : Other threads are not starting at this point!!

But we still need to sync these methods, which is a defensive design that ensures that all the relevant methods of the class are thread safe. Unfortunately, we have to consider this because the biggest problem with multithreaded programming is that we never know what's going to happen to our programs, so we should try to avoid any factors that might cause thread insecurity.

This begs the question: how can you synchronize two different methods to prevent multiple threads from affecting each other when they call these methods?

Synchronization of methods enables you to control the order in which methods are executed because a method already running on a thread cannot be invoked by another thread. The implementation of this mechanism is done by the lock of the specified object itself, since the lock of the object that the method needs to access is occupied by a thread, it is noteworthy that the so-called object lock is not actually bound to the object, but to the object instance, if two threads have two instances of the object, All of them can access the object at the same time,

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.