import java.util.concurrent.*;

public class TestSynchronized {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        SyncSample ss = new SyncSample();
        executor.execute(() -> ss.func1());
        executor.execute(() -> ss.func1());

        Thread.sleep(100);

        executor.execute(() -> ss.func2());
        executor.execute(() -> ss.func2());

        Thread.sleep(100);

        SyncSample ss2 = new SyncSample();
        executor.execute(() -> ss.func3());
        executor.execute(() -> ss2.func3());
        executor.shutdown();
    }
}

class SyncSample {
    public void func1() {
        System.out.println("Before sync this");
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        synchronized (this) {
            for (int i = 0; i < 5; i++)
                System.out.println(i);
        }
    }

    public synchronized void func2() {
        System.out.println("Before sync method");
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 5; i++)
            System.out.println(i);
    }

    public void func3() {
        System.out.println("Before sync class");
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        synchronized (SyncSample.class) {
            for (int i = 0; i < 5; i++)
                System.out.println(i);
        }
    }
}