JP Morgan Interview Question
Developer Program EngineersCountry: India
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();
}
}
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);
}
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();
}
}
}
}
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();
}
}
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();
}
}
}
}
}
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 :)
Need to have a sleep between evenworker.start() and oddworker.start(). Otherwise there is no guarantee that which worker runs first.
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();
}
}
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();
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();
}
}
// 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();
}
}
}
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();
}
}
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;
}
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;
}
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;
}
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 ~
$
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));
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
}
}
}
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();
}
}
}
}
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;
}
//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();
}
}
//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();
}
}
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();
}
}
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();
}
}
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();
}
}
Generic program with ability to set no of threads to print successive numbers
using wait and notify methods
package multithreading;
import java.io.PrintWriter;
import java.io.StringWriter;
public class MultipleNumberPrinterThreadUsingWaitNotifyOnLockObject
{
public static class NumberPrinterThread implements Runnable
{
private Object lock;
private int max, modNumber, totalThreads;
private int[] currentNumber;
public NumberPrinterThread(Object lock, int modNumber, int totalThreads, int max, int[] currentNumber)
{
this.modNumber = modNumber;
this.max = max;
this.currentNumber = currentNumber;
this.lock = lock;
this.totalThreads = totalThreads;
}
@Override
public void run()
{
int numberToPrint = modNumber;
while (numberToPrint <= max)
{
synchronized (lock)
{
while (currentNumber[0] != numberToPrint)
{
try
{
System.out.println(Thread.currentThread().getName()+" waiting");
lock.wait();
System.out.println(Thread.currentThread().getName()+" waked up");
//Uncomment for single notify
/*if(currentNumber[0] != numberToPrint) {
lock.notify();
}*/
}
catch (InterruptedException e)
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("Thread: " + modNumber + " interuppted\n"
+ sw.toString());
}
}
System.out.println(String.valueOf(numberToPrint));
numberToPrint += totalThreads;
currentNumber[0]++;
//Uncomment below for single notify implementation and comment out notifyAll
//lock.notify();
lock.notifyAll();
}
}
}
}
public static void main(String[] args)
{
Object lock = new Object();
int currentNumber[] = new int[]
{
1
}, max = 100, totalThreads = 2;
for (int i = 1; i <= totalThreads; i++)
{
new Thread(new NumberPrinterThread(lock, i, totalThreads, max, currentNumber)).start();
}
}
}
public class OddEven implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <= 10; i++) {
synchronized (this) {
if (i % 2 == 0 && Thread.currentThread().getName().equals("t2")) {
try {
notifyAll();
System.out.println("Even Thread : " + i);
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (i % 2 != 0
&& Thread.currentThread().getName().equals("t1")) {
try {
notifyAll();
System.out.println("Odd Thread : " + i);
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
OddEven obj = new OddEven();
Thread t1 = new Thread(obj, "t1");
Thread t2 = new Thread(obj, "t2");
t1.start();
t2.start();
}
}
You can use Semaphores
- Kunal June 08, 2013