Thread in monitor (BLOCKED) state waiting for synchronized access example and jvisualvm analysis


public class ThreadBlockedOnSynchronizedTest {

	public static void main(String[] args) throws InterruptedException {
		System.out.println(Thread.currentThread().getName() + " started");
		
		new Thread(() -> {
			System.out.println(Thread.currentThread().getName() + " started");
			synchSleep(10000000);
			System.out.println(Thread.currentThread().getName() + " stopped");
		}).start();
		
		Thread.sleep(50);
		synchSleep(50);
		System.out.println(Thread.currentThread().getName() + " stopped");
	}

	static synchronized void synchSleep(int i) {
		try {
			System.out.println(Thread.currentThread().getName() + " entered sync sleep");
			Thread.sleep(i);
			System.out.println(Thread.currentThread().getName() + " left sync sleep");

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}

Output:
main started
Thread-0 started
Thread-0 entered sync sleep

ThreadBlockedOnSynchronizedTest

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s