Java Thread wait and notify for Right Handed Thinkers

This code may be enough for you, but I will add a few words at the end. (note: if you use this code replace the WordPress ” with real ones)

*********************************
package com.multiple.threads;

public class Controller
{
public static void main(String[]args) throws InterruptedException
{
WorkingClass b1 =new WorkingClass();
Thread b = new Thread(b1);
b.start();
synchronized(b)
{
System.out.println(“1 Just about to call wait()” + b.getName());
b.wait();
System.out.println(“2 Just got notified”);}
System.out.println(“3 Ended here”);}}

class WorkingClass implements Runnable
{
public void run(){ synchronized (this){
System.out.println(“4 Starting a 4 sec sleep, nighty night.”);
try{ Thread.sleep(4000); }catch(Exception e){}
System.out.println(“5 Finished sleeping and calling notification”);
notify();
}}}
**********************************
output is:
1 Just about to call wait() Thread-0
4 Starting delay
5 Finished sleeping and calling notification
2 Just got notified
3 ended here

So, you have to synchronize your thread object and run() to get locks. Then the thread stops at the wait() stage and does nothing until notify() – after the task is finished. At which point it goes to the last stage in the program and finishes. – The task here is a 4 second sleep, but it could be getting data online.
Try it in your terminal window – it works.

About these ads

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