JP Morgan Interview Question for Developer Program Engineers


Country: India




Comment hidden because of low score. Click to expand.
3
of 5 vote

You can use Semaphores

package poc;

import java.util.concurrent.Semaphore;

public class ThreadevenOdd implements Runnable {
	private boolean isEven;
	private int count;
	static Semaphore s = new Semaphore(1);
	static Semaphore t = new Semaphore(0);
	ThreadevenOdd(boolean flag, int c){
		isEven = flag;
		count = c;
	}
	
	@Override
	public void run() {
		if (isEven){
			try {
				printEven(count);
			} catch (InterruptedException e) {				
				e.printStackTrace();
			}
		}else{
			try {
				printOdd(count);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	private void printOdd(int count) throws InterruptedException{
		int c = 1;
		for(int i=0;i<count;i++){
			
			s.acquire(1);
			System.out.println(c);
			c = c+2;
			t.release(1);
			
		}
		
	}
	
	private void printEven(int count) throws InterruptedException{
		int c = 2;
		for(int i=0;i<count;i++){
			
			t.acquire(1);
			System.out.println(c);
			c = c+2;
			s.release(1);
		}
		
		
	}
	
	public static void main(String[] args){
		
		
		Thread a = new Thread(new ThreadevenOdd(true,20));
		Thread b = new Thread(new ThreadevenOdd(false,20));
		a.start();
		b.start();
					
	}

}

- Kunal June 08, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

why did you use 0 as the count in Semaphore t

- mike June 09, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

This not correct way, just make c=0 to c=2 as you don't need 0 in natural number, it will print even-2 then odd-1, secondly count is for total count but individual method count (how many number to be printed).

- Dewendra-Oracle December 27, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

By using mutithreading in linux:

#include<stdio.h>
#include<pthread.h>
pthread_mutex_t mlock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
int flag=0;
void *EVEN(void *param);
void *ODD(void *param);
int main()
{
pthread_t etid,otid;
pthread_create(&etid,NULL,EVEN,NULL);
pthread_create(&otid,NULL,ODD,NULL);
pthread_exit(NULL);
}

void *EVEN(void *param)
{
int x=0;
int i;
for(i=0;i<20;i++)
{
pthread_mutex_lock(&mlock);
if(flag==1)
pthread_cond_wait(&cond,&mlock);
printf("%d ",x);
x=x+2;
flag=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mlock);
}
}

void *ODD(void *param)
{
int x=1;
int i;
for(i=0;i<20;i++)
{
pthread_mutex_lock(&mlock);
if(flag==0)
pthread_cond_wait(&cond,&mlock);
printf("%d ",x);
x=x+2;
flag=0;
pthread_mutex_unlock(&mlock);
pthread_cond_signal(&cond);
}

- Ankit June 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

asdf

- Anonymous October 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

package threads;

import java.util.concurrent.CountDownLatch;

public class EvenOddThreads {
	public static void main(String[] args)  {
		try{
		CountDownLatch latch = new CountDownLatch(1);
		Thread even = new NumberPrinter(latch, true);
		Thread odd = new NumberPrinter(latch, false);
		even.start();
		odd.start();

		even.join();
		odd.join();
		} catch(Exception e) {}
	}
	public static void main1()
	{}
}

class NumberPrinter extends Thread {
	CountDownLatch latch;
	boolean isEven;

	NumberPrinter(CountDownLatch o, boolean isEven) {
		this.latch = o;
		this.isEven = isEven;
	}

	@Override
	public void run() {
		if (isEven) {
			try {
				for (int i = 0; i <= 100; i++) {
					synchronized (latch) {
						System.out.print(" " + 2 * i);
						latch.countDown();
						latch.notify();
						if (i < 100)
							latch.wait();
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();

			}
		} else {
			try {
				latch.await();
				for (int i = 0; i < 100; i++) {
					synchronized (latch) {
						System.out.print(" " + (2 * i + 1));
						latch.notify();
						if (i < 100)
							latch.wait();
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

- Vamsi Krishna M March 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class TwoThread {
	
	int startingNumber = 1;
	int endingNumber = 20;
	int printingNumber = 1;
	
	Thread thread1 = null, thread2 = null;
	
	public TwoThread(){
		thread1 = new Thread1();
		thread2 = new Thread2();
		thread1.start();
		thread2.start();
		thread2.suspend();
	}
	
	public void end(){
		if(thread1.isAlive())
			thread1.stop();
		if(thread2.isAlive())
			thread2.destroy();
	}
	
	public class Thread1 extends Thread{
		// odd number printing thread
		@SuppressWarnings("deprecation")
		public void run(){
			while(printingNumber <= endingNumber){
				if(printingNumber%2 != 0){
					System.out.print(printingNumber+++" ");
					thread2.resume();
					thread1.suspend();
				}
			}
			if(endingNumber%2 == 0){	// let the other thread finish it's execution
				thread2.resume();
			}
		}
		
		
	}
	public class Thread2 extends Thread{
		// even number printing thread
		public void run(){
			while(printingNumber <= endingNumber){
				if(printingNumber%2 == 0){
					System.out.print(printingNumber+++" ");
					thread1.resume();
					thread2.suspend();
				}
			}
			if(endingNumber%2 != 0){	// let the other thread finish it's execution
				thread1.resume();
			}
		}
	}
	
	public static void main(String args[]){
		TwoThread tt = new TwoThread();
	}
	
}

- raghuram2404 June 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The resume and suspend methods (and the destroy method) are both deprecated because they are unsafe. You shouldn't be using them.

- Anonymous June 08, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

package com.careercup.site;

public class ThreadSynchronize {

	public static void main(String[] args) throws InterruptedException {

		Object lock = new Object();
		Runnable evenThread = new Counter(0, lock);
		Runnable oddThread = new Counter(1, lock);
		Thread evenWorker = new Thread(evenThread);
		Thread oddWorker = new Thread(oddThread);
		evenWorker.start();
		oddWorker.start();

	}

}

class Counter implements Runnable {

	private int start;
	private Object lock;

	public Counter(int seed, Object lock) {
		start = seed;
		this.lock = lock;

	}

	@Override
	public void run() {

		while (true) {
			start += 2;
			System.out.println(start);
			synchronized (lock) {
				try {
					lock.notify();
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}

	}
}

- Anonymous June 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I've added this reply. Basically, I'm using a common lock object to synchronize both the threads. Bit rusty with Threads API, though , so it too sometime for me :)

- Prabhjot June 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Need to have a sleep between evenworker.start() and oddworker.start(). Otherwise there is no guarantee that which worker runs first.

- kulbhushan verma June 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@kulbhushan verma, you are right.
1. There is no guarantee that even thread will start first.
2. When does it stop?
We can add sleep(), but I dont think thats a feasible solution here.

- Vamsi Krishna M March 19, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

System.out.print(iAmOfAnArgumentativeNature);
}

package com.mahi;

public class EvenThread implements Runnable {
public EvenOddHolder evo;

public EvenThread(EvenOddHolder evo) {
this.evo=evo;
}

public void run(){
for(int i=0;i<=10;i++)
//System.out.println(i);
try {
evo.even();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}


package com.mahi;

public class OddThread implements Runnable {
public EvenOddHolder evo;
public OddThread(EvenOddHolder evo) {
this.evo=evo;

// TODO Auto-generated constructor stub
}

public void run(){
for(int i=0;i<=10;i++)
//System.out.println(i);
try {
evo.odd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}



package com.mahi;

public class EvenOddHolder {

public int counter=1;
boolean flag=false;

public synchronized void odd() throws InterruptedException
{
while(flag==true){
wait();

}
System.out.println("odd:"+counter);
counter++;
flag=true;
notify();


}

public synchronized void even() throws InterruptedException
{
while(flag==false){



wait();


}
flag=false;
System.out.println("even:"+counter);
counter++;

notify();


}

}

- mahipal July 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

it is simple no need to use any locking or anything.

public class RCExample
    {
int maxNumber = 100;
        int number = 1;
        public void PrintEven()
        {
            while (number < maxNumber)
            {
                if (number % 2 == 0)
                {
                   // Console.WriteLine(number);
                    Console.WriteLine(Thread.CurrentThread.Name + " " + number + " ");
                    number++;
                }
            }
        }
        public void PrintOdd()
        {
            while (number < maxNumber)
            {
                if (number % 2 != 0)
                {
                 //   Console.WriteLine(number);
                    Console.WriteLine(Thread.CurrentThread.Name + " " + number + " ");
                    number++;
                }
            }
        }

    }

and

Thread evenThread = new Thread(new ThreadStart( raceCondition.PrintEven));
            evenThread.Name = "Even Thread :";
            Thread oddThread = new Thread(new ThreadStart( raceCondition.PrintOdd));
            oddThread.Name = "Odd Thread :";

            evenThread.Start();
            oddThread.Start();

- hilleybilley September 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EvenThread extends Thread{

	private int even;

	private int max;
	
	private EvenThread OddThread;

	public EvenThread(int _even, int _max)
	{
		even = _even;
		max = _max;
	}

	public void SetThread(EvenThread _oddthread)
	{
		OddThread = _oddthread;
	}

	@Override
	public void run() {
		while (even < max - 1) {
			even += 2;
			System.out.println("The even is: " + even);
			if (even == 2) {
				OddThread.start();
			}
			else
			{
				OddThread.resume();
			}
			this.suspend();
		}
	}

}

and

public class Main {

	public static void main(String[] args)
	{
		EvenThread t1 = new EvenThread(0,201);
		
		EvenThread t2 = new EvenThread(1,201);

		t1.SetThread(t2);

		t2.SetThread(t1);

		t1.start();
	}
}

- With nested structure September 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// used to signal between two threads
        private static AutoResetEvent auto1 = new AutoResetEvent(false);

        // lock needed for Printing and Set() even in one shot
        private static object synclock = new object();

        static void Main(string[] args)
        {
            System.Threading.Thread t1 = new System.Threading.Thread(printOddNum);
            System.Threading.Thread t2 = new System.Threading.Thread(printEvenNum);

            t1.Start();
            t2.Start();

            t1.Join();
            t2.Join();
        }     

        public static void printOddNum()
        {
            for (int i = 0; i < 50; i++)
            {
                if (i % 2 != 0)
                {
                    auto1.WaitOne();
                    lock (synclock)
                    {
                        Console.WriteLine(i);
                        auto1.Set();
                    }
                    
                }                
            }
        }

        public static void printEvenNum()
        {
            for (int i = 0; i < 50; i++)
            {               
                if (i % 2 == 0)
                {                    
                    lock (synclock)
                    {
                        Console.WriteLine(i);
                        auto1.Set();
                    }
                    auto1.WaitOne();
                }
            }
        }

- kshatriya December 02, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think, its working fine. I done it through Semaphore class, it can be also done with legacy thread mechanism using wait and notify.

import java.util.concurrent.Semaphore;

public class PrintEvenOddWithSemaphore {

	public static void main(String[] args) {
		Test test = new Test(new CalculateEvenOdd(10));
		Thread t1 = new Thread(test);
		Thread t2 = new Thread(test);
		t1.start();
		t2.start();
	}

}

class Test implements Runnable{
	CalculateEvenOdd evenOdd = null;
	
	public Test(CalculateEvenOdd evenOdd) {
		this.evenOdd = evenOdd;
	}
	@Override
	public void run() {
		try {
			evenOdd.calEvenOdd();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
class CalculateEvenOdd{
	private Semaphore semaphore = null;
	private int range = 10;
	
	public CalculateEvenOdd(int range) {
		semaphore = new Semaphore(2);
		this.range = range;
	}
	
	public void calEvenOdd() throws InterruptedException{
		semaphore.acquire();
		for(int i=1;i<=range;i++){
			if(i%2==0){
				System.out.println(i+" is Even Number");
			}
			else{
				System.out.println(i+" is Odd Number");
			}
		}
		semaphore.release();
	}
	
}

- Rambrij Chauhan December 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Above semaphore code prints repeated numbers.

- Vijay March 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

using C++11.

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

const int				max = 100;
std::mutex				mtx;
std::condition_variable	cv;

bool bEven = true, bOdd = false;
void countAndPrint(const int strVal, const int id) {
	int n = strVal;
	while (n < max) {
		std::unique_lock<std::mutex> lck(mtx);
		cv.wait(lck, [&]() { return n % 2 == 0 ? bEven : bOdd; });
		std::cout << "thread: " << id << ", " << n << std::endl;
		n += 2;
		bEven	= !bEven;
		bOdd	= !bOdd;
		cv.notify_one();
	}
}

int main() {
	std::thread t1(countAndPrint, 0, 0);
	std::thread t2(countAndPrint, 1, 1);
	t1.join();
	t2.join();
	std::cin.get();
	return 0;
}

- Passerby_A March 14, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.job.interview.test;

public class MyMain {

/**
* @param args
*/
public static void main(String[] args) throws Exception{
int max = 1000;
MyLock lock = new MyLock();
Thread odd = new Thread(new MyOddThread(max,lock));
Thread even = new Thread(new MyEvenThread(max,lock));
odd.start();
even.start();
even.join();
odd.join();
System.out.println("End Of Main");
}

}


class MyOddThread implements Runnable {

int max = 0;
MyLock lock;
public MyOddThread(int max,MyLock lock) {
this.max = max;
this.lock = lock;
}

@Override
public void run() {

try {
for(int i=1; i<= max; i++){

synchronized (lock) {
if(lock.isEvenPrint){
lock.wait();
}else{
if(i%2 != 0 ){
System.out.println(i);
lock.isEvenPrint = true;
lock.isOddPrint = false;
lock.notify();
}

}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}

class MyEvenThread implements Runnable {

int max = 0;
MyLock lock;
public MyEvenThread(int max,MyLock lock) {
this.max = max;
this.lock = lock;
}

@Override
public void run() {
try {
for(int i=2; i<= max; i++){
synchronized (lock) {
if(lock.isOddPrint){
lock.wait();
}else{
if(i%2 == 0 ){
System.out.println(i);
lock.isOddPrint = true;
lock.isEvenPrint = false;
lock.notify();
}

}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

class MyLock{
public boolean isEvenPrint = false;
public boolean isOddPrint = true;
}

- Jags March 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.job.interview.test;

public class MyMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		int max = 1000;
		MyLock lock = new MyLock();
		Thread odd = new Thread(new MyOddThread(max,lock));
		Thread even = new Thread(new MyEvenThread(max,lock));
		odd.start();
		even.start();
		even.join();
		odd.join();
		System.out.println("End Of Main");
	}

}


class MyOddThread implements Runnable {
	
	int max = 0;
	MyLock lock;
	public MyOddThread(int max,MyLock lock) {
		this.max = max;
		this.lock = lock;
	}
	
	@Override
	public void run() {
		
		try {
			for(int i=1; i<= max; i++){
				
				synchronized (lock) {
					if(lock.isEvenPrint){
						lock.wait();
					}else{
						if(i%2 != 0 ){
							System.out.println(i);
							lock.isEvenPrint = true;
							lock.isOddPrint = false;
							lock.notify();
						}
						
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
}

class MyEvenThread implements Runnable {
	
	int max = 0;
	MyLock lock;
	public MyEvenThread(int max,MyLock lock) {
		this.max = max;
		this.lock = lock;
	}
	
	@Override
	public void run() {
		try {
			for(int i=2; i<= max; i++){
				synchronized (lock) {
					if(lock.isOddPrint){
						lock.wait();
					}else{
						if(i%2 == 0 ){
							System.out.println(i);
							lock.isOddPrint = true;
							lock.isEvenPrint = false;
							lock.notify();
						}
						
					}
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class MyLock{
	public boolean isEvenPrint = false;
	public boolean isOddPrint = true;
}

- Anonymous March 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

GLC@GLC-Butterfly ~
$ cat pthread1.cpp
#include <iostream>
#include <pthread.h>
#include <iomanip>
using namespace std;

pthread_mutex_t mutexid=PTHREAD_MUTEX_INITIALIZER;
int prevthread=1;

void* printValue(void *arg){
        int remainder=(int)(arg);
        int i=0;
        while(i<10) {
                if(prevthread != remainder) {
                pthread_mutex_lock(&mutexid);

                if(i++%2==remainder) {
                        cout<<i-1 <<" ";
                }

                pthread_mutex_unlock(&mutexid);
                prevthread=1-prevthread;
                }
        }
        cout.flush();
}

int main()
{
        pthread_t threadid1,threadid2;

        pthread_create(&threadid1, NULL, printValue,(void*)1);
        pthread_create(&threadid2, NULL, printValue,(void*)0);

        pthread_join(threadid1,NULL);
        pthread_join(threadid2,NULL);

        pthread_exit(0);
}

GLC@GLC-Butterfly ~
$ g++ -pthread -fpermissive pthread1.cpp
pthread1.cpp: In function ‘void* printValue(void*)’:
pthread1.cpp:10:25: warning: cast from ‘void*’ to ‘int’ loses precision [-fpermissive]
  int remainder=(int)(arg);
                         ^

GLC@GLC-Butterfly ~
$ ./a.exe
0 1 2 3 4 5 6 7 8 9
GLC@GLC-Butterfly ~
$

- Kiran JG April 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Natural number series generated using N Thread


public class SeriesGeneratorDemo {
public static final int NUMBER_OF_THREAD = 5;

public static void main(String[] args) {
// TODO code application logic here
SequenceGenerator sequenceGenerator=new SequenceGenerator();
for (int i = 1; i <= NUMBER_OF_THREAD; i++) {
new Thread(sequenceGenerator,i+"").start();
}
}
}
class SequenceGenerator implements Runnable {
private static final int SERIES_MAX_NUMBER = 100;
private static int nextThreadName=1;
private static int nextNumber = 0;

@Override
public void run() {
while (nextNumber < SERIES_MAX_NUMBER) {
synchronized (this) {
int currentThread = Integer.parseInt(Thread.currentThread().getName());
if (currentThread==nextThreadName) {
generateNumber();
if (currentThread < SeriesGeneratorDemo.NUMBER_OF_THREAD) {
nextThreadName = currentThread + 1;
} else {
nextThreadName = 1;
}
this.notifyAll();
} else {
try {
this.wait();
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
}

public synchronized void generateNumber() {
System.out.println("Thread Name : "+Thread.currentThread().getName()+" value : "+ (++nextNumber));
}
}

- Roshan N P May 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.concurrent.Callable;

class Predicate implements Callable<Boolean> {
    protected Value data = null;
    Predicate(Value i) { data = i; }
    public Boolean call() {
        return true;
    }
}

class IsOdd extends Predicate {
    IsOdd(Value i) { super(i); }
    public Boolean call() {
        return data.get() % 2 != 0;
    }
}

class IsEven extends Predicate {
    IsEven(Value i) { super(i); }
    public Boolean call() {
        return data.get() % 2 == 0;
    }
}

class Value {
    private int value_ = 1;
    int get() { return value_; }
    void set(int i) { value_ = i; }
}

class Generator implements Runnable
{
    private Value next_ = null;
    private Predicate check_ = null;

    Generator(Value d, Predicate p) {
        next_ = d;
        check_ = p;
    }

    public void run()
    {
        try {
            while (next_.get() <= 100) {
                synchronized (next_) {
                    while (!check_.call())
                        next_.wait();
                    System.out.print(next_.get() + "(" + this + ")," );
                    next_.set(next_.get() + 1);
                    next_.notifyAll();
                }
            }
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class OddEvenThreads
{
    public static void main(String[] args) {
        Value v = new Value();
        Thread t1 = new Thread(new Generator(v, new IsOdd(v)));
        Thread t2 = new Thread(new Generator(v, new IsEven(v)));
        t1.start();
        t2.start();
    }
}

- imharish June 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.Scanner;

class Odd_Even_No implements Runnable{
 public int number;
 
 public int limit;
 
 Odd_Even_No(int number, int limit){
  this.number=number;
  this.limit=limit;
  }
  
  public void odd_Even(){
  
    for(int i=number; i<=number+limit;i=i+1){
	
	 if(number%2!=0 && i%2!=0){
	   
	   System.out.println(Thread.currentThread().getName()+"\t \t"+ i);
	  //notifyall();
	   Thread.yield();
	   }else if(number%2==0 && i%2==0){
		System.out.println(Thread.currentThread().getName()+"\t \t"+ i);
		//notifyall();
	    Thread.yield();
}

}
}
public void run(){
odd_Even();
}
}

public class Thread_Test3{

  public static void main(String [] args){
  Scanner scn=new Scanner(System.in);
  System.out.println("please put your start sequence and the limit\n");
  int number=scn.nextInt();
  int limit=scn.nextInt();
  
    Odd_Even_No odn1=new Odd_Even_No(number,limit);
	Odd_Even_No odn2=new Odd_Even_No(number+1,limit);
	
	Thread t1=new Thread(odn1);
	Thread t2=new Thread(odn2);
	
	if(number%2!=0){
	  t1.setName("odd_Thread");
	  t2.setName("even_Thread");
	  }
	  else{
	  t2.setName("odd_Thread");
	  t1.setName("even_Thread");
	  }
	  
	  t1.start();
	  t2.start();
	  
	  }
	  }

- gautam August 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EvenOdd {
	private static Object lock = new Object();
	private static boolean evenTurn = false;
	
	public static class EventPrinter implements Runnable
	{
		int countUpTo;
		int start = 0;
		
		public EventPrinter(int num)
		{
			this.countUpTo = num;
		}

		@Override
		public void run() {
			while(start < countUpTo)
			{
				synchronized (lock) {
					if(evenTurn)
					{
						System.out.println(start);
						start +=2;
						evenTurn = false;
					}
				}
			}
			
		}
	}
	
	public static class OddPrinter implements Runnable
	{
		int countUpTo;
		int start = 1;
		
		public OddPrinter(int num)
		{
			this.countUpTo = num;
		}

		@Override
		public void run() {
			while(start < countUpTo)
			{
				synchronized (lock) {
					if(!evenTurn)
					{
						System.out.println(start);
						start +=2;
						evenTurn = true;
					}
				}
			}	
		}
	}

	public static void main (String[] args)
	{
		evenTurn = true;
		int max = 100;
		new Thread(new EventPrinter(max)).start();
		new Thread(new OddPrinter(max)).start();
	}

}

- evenodd September 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This was the simplest solution i was looking for. Thanks everyone !!!

- Santhmr November 22, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

package Multithreading;

public class PrintOddEvenNumbers {

    volatile static int i = 1;
    static Object lock = new Object();
    static int n = 10;
    static Integer oddSemaphore = 0;
    static Integer evenSemaphore = 0;

    public static void main(String args[]) {
        Thread tOdd = new Thread() {
            @Override
            public void run() {
                while (i <= n) {
                    synchronized (lock) {
                        if (i % 2 == 0) {
                            try {
                                lock.wait();
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                            }
                        }
                        System.out.println(i++);
                        lock.notify();
                    }
                }
            }
        };


        Thread tEven = new Thread() {
            @Override
            public void run() {
                while (i <= n) {
                    synchronized (lock) {
                        if (i % 2 == 1) {
                            try {
                                lock.wait();
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                            }
                        }
                        System.out.println(i++);
                        lock.notify();
                    }
                }
            }
        };
        tOdd.start();
        tEven.start();
    }
}

- P December 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class EvenOdd {

    Boolean value = true;

    int i = 0;

    Runnable even = () -> {

        while (i < 11) {
            synchronized (value) {
                if (i % 2 == 0) {
                    System.out.println("Even : " + i);
                    i++;
                    value.notifyAll();
                    try {
                        value.wait();
                    } catch (final Exception e) {}
                }
            }
        }
    };

    Runnable odd = () -> {
        while (i < 11) {
            synchronized (value) {
                if (i % 2 == 1) {
                    System.out.println("Odd : " + i);
                    i++;
                    value.notifyAll();
                    try {
                        value.wait();
                    } catch (final Exception e) {}
                }
            }
        }
    };

    public static void main(final String[] args) {
        final EvenOdd gen = new EvenOdd();
        new Thread(gen.even).start();
        new Thread(gen.odd).start();

    }
}

- Anonymous May 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.javafries.thread;

public class EvenOddNumberPrinter {

private static class NumberPrinter {

// To check if even number is printed or not.
private boolean isEvenPrinted = true;

public void printOdd(int number) throws InterruptedException {
// Get a lock on NumberPrinter
synchronized (this) {

// Wait until even is not printed.
if (!isEvenPrinted)
wait();

System.out.println(number);

isEvenPrinted = false;

// Notify the other waiting thread which is waiting on
// NumberPrinter
// Other thread will get out of waiting state
notify();
}
}

public void printEven(int number) throws InterruptedException {
synchronized (this) {
if (isEvenPrinted)
wait();

System.out.println(number);
isEvenPrinted = true;
notify();
}
}
}

private static class OddNumberGenerator implements Runnable {
private NumberPrinter q;
private int max;

public OddNumberGenerator(NumberPrinter q, int max) {
this.q = q;
this.max = max;
}

@Override
public void run() {
for (int i = 1; i < max; i = i + 2) {
try {
q.printOdd(i);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}

private static class EvenNumberGenerator implements Runnable {
private NumberPrinter printer;
private int max;

public EvenNumberGenerator(NumberPrinter printer, int max) {
this.printer = printer;
this.max = max;
}

@Override
public void run() {
for (int i = 2; i <= max; i = i + 2) {
try {
printer.printEven(i);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}

public static void main(String[] args) {
int maxNumber = 10;
NumberPrinter printer = new NumberPrinter();

new Thread(new EvenNumberGenerator(printer, maxNumber)).start();
new Thread(new OddNumberGenerator(printer, maxNumber)).start();
}
}

- vishal naik June 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package sg.test.threads;

import java.util.concurrent.Semaphore;


public class SemaphoreEvenOdd {

public static void main(String[] args) {
Semaphore evenSemaphore = new Semaphore(1);
Semaphore oddSemaphore = new Semaphore(1);
Thread even = new Thread(new EvenThread(evenSemaphore,oddSemaphore),"Even Thread");
Thread odd = new Thread(new OddThread(evenSemaphore,oddSemaphore), "Odd Thread");
even.start();
odd.start();


}

}

class EvenThread implements Runnable{
Semaphore evenSemaphore ;
Semaphore oddSemaphore ;
public EvenThread(Semaphore e, Semaphore o) {
this.evenSemaphore = e;
this.oddSemaphore = o;

}

@Override
public void run() {
for (int k = 0; k < 20; k++) {
try{
evenSemaphore.acquire();
if(k%2 == 0){
System.out.println(Thread.currentThread().getName() +" "+ k);
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
oddSemaphore.release();
}
}
}

}

class OddThread implements Runnable{
Semaphore evenSemaphore ;
Semaphore oddSemaphore ;
public OddThread(Semaphore e, Semaphore o) {
this.evenSemaphore = e;
this.oddSemaphore = o;

}

@Override
public void run() {
for (int k = 0; k < 20; k++) {
try{
oddSemaphore.acquire();
if(k%2 == 1){
System.out.println(Thread.currentThread().getName() +" "+ k);
}
}catch(InterruptedException e){
e.printStackTrace();
}
finally{
evenSemaphore.release();
}

}
}

}

- sharad garg January 17, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package sg.test.threads;

import java.util.concurrent.Semaphore;


public class SemaphoreEvenOdd {

	public static void main(String[] args) {
		Semaphore evenSemaphore = new Semaphore(1);
		Semaphore oddSemaphore = new Semaphore(1);
		Thread even = new Thread(new EvenThread(evenSemaphore,oddSemaphore),"Even Thread");
		Thread odd = new Thread(new OddThread(evenSemaphore,oddSemaphore), "Odd Thread");
		even.start();
		odd.start();
		
		
	}

}

class EvenThread implements Runnable{
	Semaphore evenSemaphore ;
	Semaphore oddSemaphore ;
	public EvenThread(Semaphore e, Semaphore o) {
		this.evenSemaphore = e;
		this.oddSemaphore = o;
		
	}

	@Override
	public void run() {
		for (int k = 0; k < 20; k++) {
			try{
				evenSemaphore.acquire();
			if(k%2 == 0){
				System.out.println(Thread.currentThread().getName() +" "+ k);
			}
			}catch(InterruptedException e){
				e.printStackTrace();
			}finally{
				oddSemaphore.release();
			}
		}
	}
	
}

class OddThread implements Runnable{
	Semaphore evenSemaphore ;
	Semaphore oddSemaphore ;
	public OddThread(Semaphore e, Semaphore o) {
		this.evenSemaphore = e;
		this.oddSemaphore = o;
		
	}

	@Override
	public void run() {
		for (int k = 0; k < 20; k++) {
			try{
				oddSemaphore.acquire();
				if(k%2 == 1){
					System.out.println(Thread.currentThread().getName() +" "+ k);
				}
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			finally{
				evenSemaphore.release();
			}
			
		}
	}
	
}

- sg2209 January 17, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

simple solution using two semaphore variable.

#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

sem_t odd;
sem_t even;

void *print_odd(void *arg)
{
	int i;
	for (i = 1; i < 50; i += 2) {
		sem_wait(&odd);
		printf("%d\n", i);
		sem_post(&even);
	}
}

void *print_even(void *arg)
{
	int i;
	for (i = 2; i < 50; i += 2) {
		sem_wait(&even);
		printf("%d\n", i);
		sem_post(&odd);
	}
}
int main()
{
	pthread_t pid, cid;
	sem_init(&odd, 0, 1); 
	sem_init(&even, 0, 0);
	pthread_create(&pid, NULL, print_odd, NULL);
	pthread_create(&cid, NULL, print_even, NULL);
	pthread_join(pid, NULL); 
	pthread_join(cid, NULL);
	return 0;
}

- sanjiv kumar July 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Simple solution using ReentrantLock and Conditions

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class WaitAndNotify {

public static void main(String[] args) {

ReentrantLock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
Condition c2 = lock.newCondition();

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
try {
lock.lock();
for (int i = 1; i <= 10; i++) {

if (i % 2 != 0) {
System.out.println(i);
c2.signalAll();
}else{
c1.await();
}

}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
try {
lock.lock();
for (int i = 1; i <= 10; i++) {

if (i % 2 == 0) {
System.out.println(i);
c1.signalAll();
}else{
c2.await();
}

}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}

}
});
t1.start();
t2.start();
}

}

- Visakh Sreekumar June 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

//Simple solution using ReentrantLock and Condition

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class WaitAndNotify {

	public static void main(String[] args) {

		ReentrantLock lock = new ReentrantLock();
		Condition c1 = lock.newCondition();
		Condition c2 = lock.newCondition();
		
		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					lock.lock();
					for (int i = 1; i <= 10; i++) {
						
							if (i % 2 != 0) {
								System.out.println(i);
								c2.signalAll();								
							}else{
								c1.await();
							}
						
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		});
		Thread t2 = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					lock.lock();
					for (int i = 1; i <= 10; i++) {
						
							if (i % 2 == 0) {								
								System.out.println(i);
								c1.signalAll();
							}else{
								c2.await();
							}
						
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}

			}
		});
		t1.start();
		t2.start();
	}

}

- Visakh Sreekumar June 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Solution using ReentrantLock and condition

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class WaitAndNotify {

	public static void main(String[] args) {

		ReentrantLock lock = new ReentrantLock();
		Condition c1 = lock.newCondition();
		Condition c2 = lock.newCondition();
		
		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					lock.lock();
					for (int i = 1; i <= 10; i++) {
						
							if (i % 2 != 0) {
								System.out.println(i);
								c2.signalAll();								
							}else{
								c1.await();
							}
						
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		});
		Thread t2 = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					lock.lock();
					for (int i = 1; i <= 10; i++) {
						
							if (i % 2 == 0) {								
								System.out.println(i);
								c1.signalAll();
							}else{
								c2.await();
							}
						
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}

			}
		});
		t1.start();
		t2.start();
	}

}

- visakhsreekumar June 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintEvenOdd {

Lock lock;
Condition evenCondition;
Condition oddCondition;

public static void main(String[] args) {
PrintEvenOdd printEvenOdd = new PrintEvenOdd();
printEvenOdd.lock = new ReentrantLock();
printEvenOdd.evenCondition = printEvenOdd.lock.newCondition();
printEvenOdd.oddCondition = printEvenOdd.lock.newCondition();

Thread evenThread = new Thread(() -> {
printEvenOdd.printEven();
});
Thread oddThread = new Thread(() -> {
printEvenOdd.printOdd();
});
evenThread.start();
oddThread.start();
}

private void printEven() {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {

}

int i = 0;
while (i < Integer.MAX_VALUE) {
if (i % 2 == 0) {
System.out.print(i + " ");
if(i % 10 == 0)
System.out.println();
oddCondition.signal();
try {
evenCondition.await();
} catch (InterruptedException e) {

}
}
i += 1;
}
lock.unlock();
}

private void printOdd() {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {

}

int i = 0;
while (i < Integer.MAX_VALUE) {
if (i % 2 == 1) {
System.out.print(i + " ");
evenCondition.signal();
try {
oddCondition.await();
} catch (InterruptedException e) {

}
}
i += 1;
}
lock.unlock();
}

}

- Sirisha Malarapu February 15, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintEvenOdd {

	Lock lock;
	Condition evenCondition;
	Condition oddCondition;

	public static void main(String[] args) {
		PrintEvenOdd printEvenOdd = new PrintEvenOdd();
		printEvenOdd.lock = new ReentrantLock();
		printEvenOdd.evenCondition = printEvenOdd.lock.newCondition();
		printEvenOdd.oddCondition = printEvenOdd.lock.newCondition();

		Thread evenThread = new Thread(() -> {
			printEvenOdd.printEven();
		});
		Thread oddThread = new Thread(() -> {
			printEvenOdd.printOdd();
		});
		evenThread.start();
		oddThread.start();
	}

	private void printEven() {
		try {
			lock.lockInterruptibly();
		} catch (InterruptedException e) {

		}

		int i = 0;
		while (i < Integer.MAX_VALUE) {
			if (i % 2 == 0) {
				System.out.print(i + " ");
				if(i % 10 == 0)
					System.out.println();
				oddCondition.signal();
				try {
					evenCondition.await();
				} catch (InterruptedException e) {

				}
			}
			i += 1;
		}
		lock.unlock();
	}

	private void printOdd() {
		try {
			lock.lockInterruptibly();
		} catch (InterruptedException e) {

		}

		int i = 0;
		while (i < Integer.MAX_VALUE) {
			if (i % 2 == 1) {
				System.out.print(i + " ");
				evenCondition.signal();
				try {
					oddCondition.await();
				} catch (InterruptedException e) {

				}
			}
			i += 1;
		}
		lock.unlock();
	}

}

- Sirisha Malarapu February 15, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintEvenOdd {

Lock lock;
Condition evenCondition;
Condition oddCondition;

public static void main(String[] args) {
PrintEvenOdd printEvenOdd = new PrintEvenOdd();
printEvenOdd.lock = new ReentrantLock();
printEvenOdd.evenCondition = printEvenOdd.lock.newCondition();
printEvenOdd.oddCondition = printEvenOdd.lock.newCondition();

Thread evenThread = new Thread(() -> {
printEvenOdd.printEven();
});
Thread oddThread = new Thread(() -> {
printEvenOdd.printOdd();
});
evenThread.start();
oddThread.start();
}

private void printEven() {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {

}

int i = 0;
while (i < Integer.MAX_VALUE) {
if (i % 2 == 0) {
System.out.print(i + " ");
if(i % 10 == 0)
System.out.println();
oddCondition.signal();
try {
evenCondition.await();
} catch (InterruptedException e) {

}
}
i += 1;
}
lock.unlock();
}

private void printOdd() {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {

}

int i = 0;
while (i < Integer.MAX_VALUE) {
if (i % 2 == 1) {
System.out.print(i + " ");
evenCondition.signal();
try {
oddCondition.await();
} catch (InterruptedException e) {

}
}
i += 1;
}
lock.unlock();
}
}

- sirisha.malarapu February 15, 2018 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More