As we work, we invent new tools, new ideas. Being associated with this "Information technology / Software Industry" for about 5 years now, would like to share a few tools and ideas, developed out of interest or needs. Therefore this blog.

Saturday, April 4, 2009

Hello World!

Could we write a simple program to continously print "Hello... ...World" in a single line, but "Hello... " and "...World" being print by different threads? This question was asked to me by one of my collegue (thanks to Saikat Manna).

Here is as an attempt (pardon me Saikat, is anything wrong! :D) :

import static java.lang.System.out;

/**
 * @author Kaushik Roy
 *
 */
public final class HelloWorldThread {
private static volatile String state = "HELLO";
/**
* @author Kaushik Roy
*
*/
static class HelloThread implements Runnable {
private Object  mutex;
/**
   * @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (true) {
if ("HELLO".equals(state)) {
synchronized (mutex) {
out.print("Hello ... ");
state = "WORLD";
try {
mutex.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
  }
/**
* @param mutex
*/
public HelloThread(Object mutex) {
this.mutex = mutex;
}
  }
/**
* @author Kaushik Roy
*
*/
static class WorldThread implements Runnable {
private Object          mutex;
/**
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (true) {
if ("WORLD".equals(state)) {
synchronized (mutex) {
out.println(" ... World");
state = "HELLO";
mutex.notify();
}
}
}
}
/**
* @param mutex
*/
public WorldThread(Object mutex) {
this.mutex = mutex;
}
}
/**
* @param args
*/
public static void main(String[] args) {
Object mutex = new Object();

new Thread(new HelloThread(mutex)).start();
new Thread(new WorldThread(mutex)).start();
}
}

Hope this works! Here goes the sample 'output':

Hello ...  ... World
Hello ...  ... World
Hello ...  ... World
Hello ...  ... World
Hello ...  ... World
Hello ...  ... World
Hello ...  ... World
Hello ...  ... World
Hello ...  ... World

Nothing great about the output. This is a very simple example illustrating the use of wait( ) and notify( ) methods with a mutex. Sun tutorial's Producer-Consumer example is a better one.

PS: This article is for Kiran Wali.

No comments:

Post a Comment

Followers

Archives