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.
synchronized means exclusive control. ,
Exclusive control = Preventing multiple processes (or threads) from entering at the same time
It seems.
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!"");
    }
}

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.
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!"");
    }
}

You can now enter one by one!
http://www.techscore.com/tech/Java/JavaSE/Thread/3/
Recommended Posts