works:programmer:java:synchronized

Ключевое слово synchronized, и как его использовать

import static java.lang.System.out;
 
public class HelloWorld {
 
    private class State {
        private int state = 0;
        private final Object lock = new Object();
        public void setState(int value) {
            synchronized (lock) {
                state = value;
            }
        }
        public int getState() {
            synchronized (lock) {
                return state;
            }
        }
    }
 
    public HelloWorld() {
 
        State st = new State();
        try {
            asyncState(st);
            while (st.getState() < 1) {
                Thread.sleep(1000);
                out.println("tick");
            }
            out.println("state set to 1");
        } catch (InterruptedException err) {
            out.println(String.valueOf(err));
        }
    }
 
    void asyncState(State state) {
        Thread th = new Thread(() -> {
            try {
                Thread.sleep(5000);
                state.setState(1);
                out.println("thread set state 1");
            } catch (InterruptedException err) {
                out.println(String.valueOf(err));
            }
        });
        out.println("before thread start");
        th.start();
        out.println("after thread start");
    }
 
    public static void main(String []args){
        new HelloWorld();
    }
 
}

Результат выполнения будет следующий.

$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
before thread start
after thread start
tick
tick
tick
tick
thread set state 1
tick
state set to 1
works/programmer/java/synchronized.txt · Last modified: 2021/06/16 09:31 by Chugreev Eugene