Otanikotani
6/19/2015 - 10:30 AM

gistfile1.java

import org.junit.Test;

public class IsSynchronizedOnMethdodsSharedForTheWholeObjectTest {

    public static class TwoMethods {

        public synchronized void wait5Secs() {
            try {
                Thread.sleep(5_000);
                System.out.println("Waited 5 secs");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public synchronized void wait10Secs() {
            try {
                Thread.sleep(10_000);
                System.out.println("Waited 10 secs");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    @Test
    public void testSynchronized() throws InterruptedException {

        final TwoMethods twoMethods = new TwoMethods();
        Runnable call5 = new Runnable() {
            @Override
            public void run() {
                twoMethods.wait5Secs();
            }
        };
        Thread thread = new Thread(call5);
        thread.start();
        twoMethods.wait10Secs();
        thread.join();
    }
}