[JAVA] synchronized notes

If you look at the code for refactoring I saw it several times and found something I forgot, so I made a note so that I wouldn't forget it.

What is synchronized?

synchronized means exclusive control. ,

Exclusive control = Preventing multiple processes (or threads) from entering at the same time

It seems.

Try out

Because it didn't come nicely with just words I tried it directly.

As a premise image It is an image of a family taking a bath one by one. (Do not enter until one person is finished.)

"Main class with main method"

MainClass.java


public class MainClass {
    public static void main(String[] args) {
        Bathroom bathroom = new Bathroom();
        FamilyTread father = new FamilyTread(bathroom, "father");
        FamilyTread mother = new FamilyTread(bathroom, "mother");
        FamilyTread sister = new FamilyTread(bathroom, "sister");
        FamilyTread me = new FamilyTread(bathroom, "I");

        father.start();
        mother.start();
        sister.start();
        me.start();
    }

}

"Class for families inheriting Thread ""

FamilyTread.java


class FamilyTread extends Thread {
    private Bathroom mBathroom;
    private String mName;

    FamilyTread(Bathroom bathroom, String name) {
        this.mBathroom = bathroom;
        this.mName = name;
    }

    public void run() {
        mBathroom.openDoor(mName);
    }

}

"A class called by a family class to work"

class Bathroom {
    void openDoor(String name) {
        System.out.println(name + ""I'll take a bath!"");
        for (int count = 0; count < 100000; count++) {
            if (count == 1000) {
                System.out.println(name + ""I took a bath."");
            }
        }
        System.out.println(name + ""I got out of the bath!"");
    }
}
Result of running several times

スクリーンショット 2016-12-12 17.17.56.png

My dad is still in the bath ...! The order has been messed up. (It happens to be in the correct order)

Therefore, using synchronized can prevent you from taking a bath (thread) at the same time.

Try using synchronized

I tried adding synchronized to the ʻopenDoor method of theBathroom` class.

class Bathroom {
    synchronized void openDoor(String name) {
        System.out.println(name + ""I'll take a bath!"");
        for (int count = 0; count < 100000; count++) {
            if (count == 1000) {
                System.out.println(name + ""I took a bath."");
            }
        }
        System.out.println(name + ""I got out of the bath!"");
    }
}
result

スクリーンショット 2016-12-12 17.30.31.png

You can now enter one by one!

reference

http://www.techscore.com/tech/Java/JavaSE/Thread/3/

Recommended Posts

synchronized notes
JUnit 4 notes
Jigsaw study notes
[wip] Docker notes
Java Generics (Notes)
JavaFX study notes
db connection notes
[Java] Array notes
Ruby Hash notes
Enum review notes
Docker study notes
DDD personal notes
[Java] Study notes
Graal related notes
Java serialization notes
html & rails notes