Wednesday, 18 December 2019

How to print hello world sequentially using thread in java.

package kp;

public class HelloWorldByWaitNotify {

public static void main(String[] args) {
Object o = new Object();
World worldObj = new World(o);
Hello hello = new Hello(worldObj);
Thread helloThread = new Thread(hello);
Thread worldThread = new Thread(worldObj);
helloThread.start();
worldThread.start();
Thread helloThread1 = new Thread(hello);
Thread worldThread1 = new Thread(worldObj);
helloThread1.start();
worldThread1.start();
}
}

class Hello implements Runnable {
World worldObj;

public Hello(World worldObj) {
this.worldObj = worldObj;
}

@Override
public void run() {
while (true) {
synchronized (worldObj) {
if (!this.worldObj.isWorld) {
System.out.println("Hello");
this.worldObj.isWorld = true;
worldObj.notify();
}
}
}
}
}

class World implements Runnable {
public boolean isWorld = false;
Object o;

public World(Object o) {
this.o = o;
}

@Override
public void run() {
while (true) {
synchronized (this) {
try {
if (!this.isWorld) {
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("WORLD!!!!!!");
this.isWorld = false;
}
}
}
}

No comments:

Post a Comment