Clean Java

There is always a bigger game

Splitting tasks among threads.

with 2 comments

Recently in an interview I was asked to write a program which prints running positive numbers, odd number shall be printed by one thread and even number shall be printed by another thread. I thought to share the program with you guys.


package org.sanju;

/**
 *
 * @author sanju.org
 *
 * Example program which prints odd number by one thread
 * and even number by another thread.
 *
 *
 */
public class SplitTaskExample {

	private volatile Integer i = new Integer(0);

	private void printRunningNumbers(){

		//odd thread
		new Thread(new Runnable() {
			public void run() {
				while(true){
					if(i % 2 == 1){
						System.out.println("odd thread :"+i);
						i++;
					}
					try{
						i.wait();
						i.notifyAll();
					}catch (Exception e) {
					}
				}
			}
		}).start();

		//even thread
		new Thread(new Runnable() {

			public void run() {
				while(true){
					if(i % 2 == 0){
						System.out.println("even thread : "+i);
						i++;
					}
					try{
						i.wait();
						i.notifyAll();
					}catch (Exception e) {
					}
				}
			}
		}).start();

	}

	public static void main(String[] args) {
		new SplitTaskExample().printRunningNumbers();
	}

}

/local/opt/java SplitTaskExample

even thread : 0
odd thread :1
even thread : 2
odd thread :3
even thread : 4
odd thread :5

Advertisements

Written by cleanjava

March 21, 2012 at 7:36 pm

2 Responses

Subscribe to comments with RSS.

  1. […] Splitting tasks among threads. (cleanjava.wordpress.com) […]

  2. […] Splitting tasks among threads. (cleanjava.wordpress.com) […]


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

%d bloggers like this: