Tag Archives: java synchonized

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);
System.out.println(“1 Just about to call wait()” + b.getName());
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”);
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.