Thread in waiting state example and jvisualvm analysis

public class ThreadWaitingTest {

	static Object monitor = new Object();
	
	public static void main(String[] args) throws InterruptedException {
		
		System.out.println(Thread.currentThread().getName() + " started");
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + " started");
				sleep(10000000);
				synchronized(monitor) {
					System.out.println(Thread.currentThread().getName() + " in sync section before notify");
					monitor.notify();
					System.out.println(Thread.currentThread().getName() + " in sync section before after");
				}
				System.out.println(Thread.currentThread().getName() + " stopped");
			}
		}).start();
	
		synchronized(monitor) {
			System.out.println(Thread.currentThread().getName() + " in sync section before wait");
			monitor.wait();
			System.out.println(Thread.currentThread().getName() + " in sync section after wait");
		}
		
		System.out.println(Thread.currentThread().getName() + " stopped");
	}

	
	private static void sleep(int i) {
		try {
			Thread.sleep(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output:
main started
main in sync section before wait
Thread-0 started

ThreadWaitingTest

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