Print Even Odd Number Two Threads Java

Print Even Odd Number Two Threads Java

Now a days this question is very popular among the companies during first round screening process to check candidate programming ability. Question detail is below:

Please implement a program that launches two threads.The fist will increment a global int by one when it is even, the second will increment the same global int by one when it is odd. the program should accept a parameter to indicate the value of the global int to terminate execution . please provide two implementations, one using standard locking mechanism and the other using lock-less techniques.

Below sample java program where lock has been created on class level, two separate thread is created where first thread will increment the number if its even and its not event then he will notify second thread and wait to get his chance again. Second there will increment the number if it’s odd if not then he will notify first thread vice-versa.

  • TwoThreadEvenOddIncrement.java using lock:
package com.thread;

public class TwoThreadEvenOddIncrement {
	
	private int startValue = 1;
	private static Object lock = new Object();
	private static int commonValue = 21;

    public static void main(String[] args) {
    	
    	TwoThreadEvenOddIncrement threadEvenOddIncrement = new TwoThreadEvenOddIncrement();
        
    	Thread t1 = threadEvenOddIncrement.threadOne(commonValue);
        Thread t2 = threadEvenOddIncrement.threadTwo(commonValue);
        
        try {
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            System.out.println("\nIncrement done");
            
        } catch (Exception e) {

        }
    }
    
    private Thread threadOne(int value) {
		
		Thread t1 = new Thread(new Runnable() {
            public void run() {

            	 while(startValue <= commonValue ) {
                    synchronized (lock) {                        
                        try {
                        	if(startValue%2 == 0){
                            	System.out.print("Thread 1 Even number: " + startValue+"\n");
                            	startValue++;                                
                            } else{
                            	lock.notify();
                            	if (startValue == commonValue) break;
                                lock.wait();
                            }
                            
                            
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
		
		return t1;
	}

	private Thread threadTwo(int value) {
		
		Thread t2 = new Thread(new Runnable() {
            public void run() {

                while(startValue <= commonValue) {
                    synchronized (lock) {
                        try {                            
                            if(startValue%2 != 0){
                            	System.out.print("Thread 2 Odd number: " + startValue+"\n");
                            	startValue++;                                
                            } else{
                            	lock.notify();
                            	lock.wait();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
		
		return t2;
	}	

}
  • Output:

Print Even Odd Number Two Threads Java

  • PrintEvenOddWithoutLock.java: Without using lock
package com.thread;

public class PrintEvenOddWithoutLock {
	
	private int value = 1;
	
	public static void main(String[] args) {
		
		PrintEvenOddWithoutLock printEvenOddWithoutLock = new PrintEvenOddWithoutLock();
		
		int commonNuber = 11000;
		
		Thread t = printEvenOddWithoutLock.thread1(commonNuber);
		Thread t2 = printEvenOddWithoutLock.thread2(commonNuber);
		
		t.start();
		t2.start();

	}	

	private Thread thread1(int commonNuber) {
		Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while (value <= commonNuber) {
					
					if (value%2!=0) {
						System.out.println("Odd number Thread 1--> "+value++);						
					}
				}
				
			}
		});
		return t;
	}
	
	private Thread thread2(int commonNuber) {
		
		
		
		Thread t2 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while (value <= commonNuber) {
					if (value%2==0) {
						System.out.println("Even number Thread 2--> "+value++);							
					}
				}
				
			}
		});
		return t2;
	}

}
  • Output:

Print Even Odd Number Two Threads Java

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *