Reputation: 1481
I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result.
This is mainly to print even and odd values in sequence.
public class PrintEvenOddTester {
public static void main(String ... args){
Printer print = new Printer(false);
Thread t1 = new Thread(new TaskEvenOdd(print));
Thread t2 = new Thread(new TaskEvenOdd(print));
t1.start();
t2.start();
}
}
class TaskEvenOdd implements Runnable {
int number=1;
Printer print;
TaskEvenOdd(Printer print){
this.print = print;
}
@Override
public void run() {
System.out.println("Run method");
while(number<10){
if(number%2 == 0){
System.out.println("Number is :"+ number);
print.printEven(number);
number+=2;
}
else {
System.out.println("Number is :"+ number);
print.printOdd(number);
number+=2;
}
}
}
}
class Printer {
boolean isOdd;
Printer(boolean isOdd){
this.isOdd = isOdd;
}
synchronized void printEven(int number) {
while(isOdd){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even:"+number);
isOdd = true;
notifyAll();
}
synchronized void printOdd(int number) {
while(!isOdd){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd:"+number);
isOdd = false;
notifyAll();
}
}
Can someone help me in fixing this?
EDIT Expected result: Odd:1 Even:2 Odd:3 Even:4 Odd:5 Even:6 Odd:7 Even:8 Odd:9
Upvotes: 24
Views: 180160
Reputation: 281
We can print odd and even using two separate threads using CompletableFuture
as well:
import java.util.concurrent.CompletableFuture;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class OddEvenBy2Thread {
private static Object object = new Object();
private static IntPredicate evenCondition = e -> e % 2 == 0;
private static IntPredicate oddCondition = e -> e % 2 != 0;
public static void main(String[] args) throws InterruptedException {
// Odd number printer
CompletableFuture.runAsync(() -> OddEvenBy2Thread.printNumber(oddCondition));
// Even number printer
CompletableFuture.runAsync(() -> OddEvenBy2Thread.printNumber(evenCondition));
Thread.sleep(1000);
}
public static void printNumber(IntPredicate condition){
IntStream.rangeClosed(1, 10).filter(condition).forEach(OddEvenBy2Thread::execute);
}
public static void execute(int num){
synchronized (object){
try{
System.out.println(Thread.currentThread().getName()+" : "+num);
object.notify();
object.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
Upvotes: 0
Reputation: 269
Use this following very simple JAVA 8 Runnable Class feature
public class MultiThreadExample {
static AtomicInteger atomicNumber = new AtomicInteger(1);
public static void main(String[] args) {
Runnable print = () -> {
while (atomicNumber.get() < 10) {
synchronized (atomicNumber) {
if ((atomicNumber.get() % 2 == 0) && "Even".equals(Thread.currentThread().getName())) {
System.out.println("Even" + ":" + atomicNumber.getAndIncrement());
} //else if ((atomicNumber.get() % 2 != 0) && "Odd".equals(Thread.currentThread().getName()))
else {System.out.println("Odd" + ":" + atomicNumber.getAndIncrement());
}
}
}
};
Thread t1 = new Thread(print);
t1.setName("Even");
t1.start();
Thread t2 = new Thread(print);
t2.setName("Odd");
t2.start();
}
}
Upvotes: 23
Reputation: 324
The solution below is using java 8 completable future and executor service to print even and odd numbers using two threads.
ExecutorService firstExecutorService = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r);
t.setName("first");
return t;
});
ExecutorService secondExecutorService = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r);
t.setName("second");
return t;
});
IntStream.range(1, 101).forEach(num -> {
CompletableFuture<Integer> thenApplyAsync = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {
if (x % 2 == 1) {
System.out.println(x + " " + Thread.currentThread().getName());
}
return num;
}, firstExecutorService);
thenApplyAsync.join();
CompletableFuture<Integer> thenApplyAsync2 = CompletableFuture.completedFuture(num).thenApplyAsync(x -> {
if (x % 2 == 0) {
System.out.println(x + " " + Thread.currentThread().getName());
}
return num;
}, secondExecutorService);
thenApplyAsync2.join();
});
firstExecutorService.shutdown();
secondExecutorService.shutdown();
The below is the console log of it.
Upvotes: 0
Reputation: 661
This solution works for me (Java 8 and above used Lamda expression)
public class EvenOddUsingThread {
static int number = 100;
static int counter = 1;
public static void main(String[] args) {
EvenOddUsingThread eod = new EvenOddUsingThread();
Thread t1 = new Thread(() -> eod.printOdd());
Thread t2 = new Thread(() -> eod.printEven());
t1.start();
t2.start();
}
public void printOdd() {
synchronized (this) {
while (counter < number) {
if (counter % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
// Print the number
System.out.println(counter + " Thread Name: " + Thread.currentThread().getName());
// Increment counter
counter++;
// Notify to second thread
notify();
}
}
}
public void printEven() {
synchronized (this) {
while (counter < number) {
if (counter % 2 == 1) {
try {
wait();
} catch (InterruptedException ignored) {
}
}
// Print the number
System.out.println(counter + " Thread Name: " + Thread.currentThread().getName());
// Increment counter
counter++;
// Notify to second thread
notify();
}
}
}
}
Upvotes: 0
Reputation: 51
class PrintNumberTask implements Runnable {
Integer count;
Object lock;
PrintNumberTask(int i, Object object) {
this.count = i;
this.lock = object;
}
@Override
public void run() {
while (count <= 10) {
synchronized (lock) {
if (count % 2 == 0) {
System.out.println(count);
count++;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(count);
count++;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
Upvotes: 0
Reputation: 69
Simplest Solution!!
public class OddEvenWithThread {
public static void main(String a[]) {
Thread t1 = new Thread(new OddEvenRunnable(0), "Even Thread");
Thread t2 = new Thread(new OddEvenRunnable(1), "Odd Thread");
t1.start();
t2.start();
}
}
class OddEvenRunnable implements Runnable {
Integer evenflag;
static Integer number = 1;
static Object lock = new Object();
OddEvenRunnable(Integer evenFlag) {
this.evenflag = evenFlag;
}
@Override
public void run() {
while (number < 10) {
synchronized (lock) {
try {
while (number % 2 != evenflag) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + number);
number++;
lock.notifyAll();
}
}
}
}
Upvotes: 3
Reputation: 71
This is easiest solution for this problem.
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();
}
}
Upvotes: 3
Reputation: 19
1- The number is initialized with 1 and isOdd
flag is set to false. set isOdd
to true
2- Increment should be by 1 (not by 2) i.e number+=1
;
Upvotes: -1
Reputation: 902
This is my solution to the problem. I have two classes implementing Runnable
, one prints odd sequence and the other prints even. I have an instance of Object
, that I use for lock. I initialize the two classes with the same object. There is a synchronized block
inside the run method of the two classes, where, inside a loop, each method prints one of the numbers, notifies the other thread, waiting for lock on the same object and then itself waits for the same lock again.
The classes :
public class PrintEven implements Runnable{
private Object lock;
public PrintEven(Object lock) {
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
for (int i = 2; i <= 10; i+=2) {
System.out.println("EVEN:="+i);
lock.notify();
try {
//if(i!=10) lock.wait();
lock.wait(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class PrintOdd implements Runnable {
private Object lock;
public PrintOdd(Object lock) {
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
for (int i = 1; i <= 10; i+=2) {
System.out.println("ODD:="+i);
lock.notify();
try {
//if(i!=9) lock.wait();
lock.wait(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class PrintEvenOdd {
public static void main(String[] args){
Object lock = new Object();
Thread thread1 = new Thread(new PrintOdd(lock));
Thread thread2 = new Thread(new PrintEven(lock));
thread1.start();
thread2.start();
}
}
The upper limit in my example is 10. Once the odd thread prints 9 or the even thread prints 10, then we don't need any of the threads to wait any more. So, we can handle that using one if-block
. Or, we can use the overloaded wait(long timeout)
method for the wait to be timed out.
One flaw here though. With this code, we cannot guarantee which thread will start execution first.
Another example, using Lock and Condition
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockConditionOddEven {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Condition evenCondition = lock.newCondition();
Condition oddCondition = lock.newCondition();
Thread evenThread = new Thread(new EvenPrinter(10, lock, evenCondition, oddCondition));
Thread oddThread = new Thread(new OddPrinter(10, lock, evenCondition, oddCondition));
oddThread.start();
evenThread.start();
}
static class OddPrinter implements Runnable{
int i = 1;
int limit;
Lock lock;
Condition evenCondition;
Condition oddCondition;
public OddPrinter(int limit) {
super();
this.limit = limit;
}
public OddPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) {
super();
this.limit = limit;
this.lock = lock;
this.evenCondition = evenCondition;
this.oddCondition = oddCondition;
}
@Override
public void run() {
while( i <=limit) {
lock.lock();
System.out.println("Odd:"+i);
evenCondition.signal();
i+=2;
try {
oddCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
static class EvenPrinter implements Runnable{
int i = 2;
int limit;
Lock lock;
Condition evenCondition;
Condition oddCondition;
public EvenPrinter(int limit) {
super();
this.limit = limit;
}
public EvenPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) {
super();
this.limit = limit;
this.lock = lock;
this.evenCondition = evenCondition;
this.oddCondition = oddCondition;
}
@Override
public void run() {
while( i <=limit) {
lock.lock();
System.out.println("Even:"+i);
i+=2;
oddCondition.signal();
try {
evenCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
}
Upvotes: 0
Reputation: 114
See the Clean implementation
public class PrintOddEvenByTwoThreads {
static int number = 1;
static Thread odd;
static Thread even;
static int max = 10;
static class OddThread extends Thread {
@Override
public void run() {
while (number <= max) {
if (number % 2 == 1) {
System.out.println(Thread.currentThread() + "" + number++);
} else {
synchronized (odd) {
synchronized (even) {
even.notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
static class EvenThread extends Thread {
@Override
public void run() {
while (number <= max) {
if (number % 2 == 0) {
System.out.println(Thread.currentThread() + "" + number++);
} else {
synchronized (even) {
synchronized (odd) {
odd.notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
odd = new OddThread();
even = new EvenThread();
odd.start();
even.start();
}
}
Upvotes: -1
Reputation: 737
Simple Solution below:-
package com.test;
class MyThread implements Runnable{
@Override
public void run() {
int i=1;
while(true) {
String name=Thread.currentThread().getName();
if(name.equals("task1") && i%2!=0) {
System.out.println(name+"::::"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else if(name.equals("task2") && i%2==0){
System.out.println(name+"::::"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
}
}
public static void main(String[] args) {
MyThread task1=new MyThread();
MyThread task2=new MyThread();
Thread t1=new Thread(task1,"task1");
Thread t2=new Thread(task2,"task2");
t1.start();
t2.start();
}
}
Upvotes: -2
Reputation: 567
This code will also work fine.
class Thread1 implements Runnable {
private static boolean evenFlag = true;
public synchronized void run() {
if (evenFlag == true) {
printEven();
} else {
printOdd();
}
}
public void printEven() {
for (int i = 0; i <= 10; i += 2) {
System.out.println(i+""+Thread.currentThread());
}
evenFlag = false;
}
public void printOdd() {
for (int i = 1; i <= 11; i += 2) {
System.out.println(i+""+Thread.currentThread());
}
evenFlag = true;
}
}
public class OddEvenDemo {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread td1 = new Thread(t1);
Thread td2 = new Thread(t1);
td1.start();
td2.start();
}
}
Upvotes: 1
Reputation: 79
public class Main {
public static void main(String[] args) throws Exception{
int N = 100;
PrintingThread oddNumberThread = new PrintingThread(N - 1);
PrintingThread evenNumberThread = new PrintingThread(N);
oddNumberThread.start();
// make sure that even thread only start after odd thread
while (!evenNumberThread.isAlive()) {
if(oddNumberThread.isAlive()) {
evenNumberThread.start();
} else {
Thread.sleep(100);
}
}
}
}
class PrintingThread extends Thread {
private static final Object object = new Object(); // lock for both threads
final int N;
// N determines whether given thread is even or odd
PrintingThread(int N) {
this.N = N;
}
@Override
public void run() {
synchronized (object) {
int start = N % 2 == 0 ? 2 : 1; // if N is odd start from 1 else start from 0
for (int i = start; i <= N; i = i + 2) {
System.out.println(i);
try {
object.notify(); // will notify waiting thread
object.wait(); // will make current thread wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Upvotes: 0
Reputation: 57
Simpler Version in Java 8:
public class EvenOddPrinter {
static boolean flag = true;
public static void main(String[] args) {
Runnable odd = () -> {
for (int i = 1; i <= 10;) {
if(EvenOddPrinter.flag) {
System.out.println(i);
i+=2;
EvenOddPrinter.flag = !EvenOddPrinter.flag;
}
}
};
Runnable even = () -> {
for (int i = 2; i <= 10;) {
if(!EvenOddPrinter.flag) {
System.out.println(i);
i+=2;
EvenOddPrinter.flag = !EvenOddPrinter.flag;
}
}
};
Thread t1 = new Thread(odd, "Odd");
Thread t2 = new Thread(even, "Even");
t1.start();
t2.start();
}
}
Upvotes: 1
Reputation: 81
Simple solution :)
package com.code.threads;
public class PrintOddEven extends Thread {
private Object lock;
static volatile int count = 1;
PrintOddEven(Object lock) {
this.lock = lock;
}
@Override
public void run () {
while(count <= 10) {
if (count % 2 == 0) {
synchronized(lock){
System.out.println("Even - " + count);
++count;
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
synchronized(lock){
System.out.println("Odd - " + count);
++count;
lock.notify();
}
}
}
}
public static void main(String[] args) {
Object obj = new Object();
PrintOddEven even = new PrintOddEven(obj);
PrintOddEven odd = new PrintOddEven(obj);
even.start();
odd.start();
}
}
Upvotes: 0
Reputation: 101
I could not understand most of the codes that were here so I wrote myself one, maybe it helps someone like me:
NOTE: This does not use separate print even and odd method. One method print() does it all.
public class test {
private static int START_INT = 1;
private static int STOP_INT = 10;
private static String THREAD_1 = "Thread A";
private static String THREAD_2 = "Thread B";
public static void main(String[] args) {
SynchronizedRepository syncRep = new SynchronizedRepository(START_INT,STOP_INT);
Runnable r1 = new EvenOddWorker(THREAD_1,syncRep);
Runnable r2 = new EvenOddWorker(THREAD_2,syncRep);
Thread t1 = new Thread(r1, THREAD_1);
Thread t2 = new Thread(r2, THREAD_2);
t1.start();
t2.start();
}
}
public class SynchronizedRepository {
private volatile int number;
private volatile boolean isSlotEven;
private int startNumber;
private int stopNumber;
public SynchronizedRepository(int startNumber, int stopNumber) {
super();
this.number = startNumber;
this.isSlotEven = startNumber%2==0;
this.startNumber = startNumber;
this.stopNumber = stopNumber;
}
public synchronized void print(String threadName) {
try {
for(int i=startNumber; i<=stopNumber/2; i++){
if ((isSlotEven && number % 2 == 0)||
(!isSlotEven && number % 2 != 0)){
System.out.println(threadName + " "+ number);
isSlotEven = !isSlotEven;
number++;
}
notifyAll();
wait();
}
notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class EvenOddWorker implements Runnable {
private String threadName;
private SynchronizedRepository syncRep;
public EvenOddWorker(String threadName, SynchronizedRepository syncRep) {
super();
this.threadName = threadName;
this.syncRep = syncRep;
}
@Override
public void run() {
syncRep.print(threadName);
}
}
Upvotes: 0
Reputation: 950
Please use the following code to print odd and even number in a proper order along with desired messages.
package practice;
class Test {
private static boolean oddFlag = true;
int count = 1;
private void oddPrinter() {
synchronized (this) {
while(true) {
try {
if(count < 10) {
if(oddFlag) {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + ": " + count++);
oddFlag = !oddFlag;
notifyAll();
}
else {
wait();
}
}
else {
System.out.println("Odd Thread finished");
notify();
break;
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void evenPrinter() {
synchronized (this) {
while (true) {
try {
if(count < 10) {
if(!oddFlag) {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + ": " + count++);
oddFlag = !oddFlag;
notify();
}
else {
wait();
}
}
else {
System.out.println("Even Thread finished");
notify();
break;
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException{
final Test test = new Test();
Thread t1 = new Thread(new Runnable() {
public void run() {
test.oddPrinter();
}
}, "Thread 1");
Thread t2 = new Thread(new Runnable() {
public void run() {
test.evenPrinter();
}
}, "Thread 2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Main thread finished");
}
}
Upvotes: 0
Reputation: 319
package example;
public class PrintSeqTwoThreads {
public static void main(String[] args) {
final Object mutex = new Object();
Thread t1 = new Thread() {
@Override
public void run() {
for (int j = 0; j < 10;) {
synchronized (mutex) {
System.out.println(Thread.currentThread().getName() + " " + j);
j = j + 2;
mutex.notify();
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
for (int j = 1; j < 10;) {
synchronized (mutex) {
System.out.println(Thread.currentThread().getName() + " " + j);
j = j + 2;
mutex.notify();
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t1.start();
t2.start();
}
}
Upvotes: 0
Reputation: 49
import java.util.concurrent.Semaphore;
public class PrintOddAndEven {
private static class OddThread extends Thread {
private Semaphore semaphore;
private Semaphore otherSemaphore;
private int value = 1;
public OddThread(Semaphore semaphore, Semaphore otherSemaphore) {
this.semaphore = semaphore;
this.otherSemaphore = otherSemaphore;
}
public void run() {
while (value <= 100) {
try {
// Acquire odd semaphore
semaphore.acquire();
System.out.println(" Odd Thread " + value + " " + Thread.currentThread().getName());
} catch (InterruptedException excetion) {
excetion.printStackTrace();
}
value = value + 2;
// Release odd semaphore
otherSemaphore.release();
}
}
}
private static class EvenThread extends Thread {
private Semaphore semaphore;
private Semaphore otherSemaphore;
private int value = 2;
public EvenThread(Semaphore semaphore, Semaphore otherSemaphore) {
this.semaphore = semaphore;
this.otherSemaphore = otherSemaphore;
}
public void run() {
while (value <= 100) {
try {
// Acquire even semaphore
semaphore.acquire();
System.out.println(" Even Thread " + value + " " + Thread.currentThread().getName());
} catch (InterruptedException excetion) {
excetion.printStackTrace();
}
value = value + 2;
// Release odd semaphore
otherSemaphore.release();
}
}
}
public static void main(String[] args) {
//Initialize oddSemaphore with permit 1
Semaphore oddSemaphore = new Semaphore(1);
//Initialize evenSempahore with permit 0
Semaphore evenSempahore = new Semaphore(0);
OddThread oddThread = new OddThread(oddSemaphore, evenSempahore);
EvenThread evenThread = new EvenThread(evenSempahore, oddSemaphore);
oddThread.start();
evenThread.start();
}
}
Upvotes: -2
Reputation: 23
package programs.multithreading;
public class PrintOddEvenNoInSequence {
final int upto;
final PrintOddEvenNoInSequence obj;
volatile boolean oddFlag,evenFlag;
public PrintOddEvenNoInSequence(int upto){
this.upto = upto;
obj = this;
oddFlag = true;
evenFlag = false;
}
void printInSequence(){
Thread odd = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 1; i <= upto; i = i + 2){
synchronized (obj) {
while(!oddFlag){
try {
obj.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Odd:"+i);
oddFlag = false;
evenFlag = true;
obj.notify();
}
}
}
});
Thread even = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 2; i <= upto; i = i + 2){
synchronized (obj) {
while(!evenFlag){
try {
obj.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Even:"+i);
oddFlag = true;
evenFlag = false;
obj.notify();
}
}
}
});
odd.start();
even.start();
}
public static void main(String[] args) {
new PrintOddEvenNoInSequence(100).printInSequence();
}
}
Upvotes: -1
Reputation: 2925
public class OddAndEvenThreadProblems {
private static Integer i = 0;
public static void main(String[] args) {
new EvenClass().start();
new OddClass().start();
}
public static class EvenClass extends Thread {
public void run() {
while (i < 10) {
synchronized (i) {
if (i % 2 == 0 ) {
try {
Thread.sleep(1000);
System.out.println(" EvenClass " + i);
i = i + 1;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
public static class OddClass extends Thread {
@Override
public void run() {
while (i < 10) {
synchronized (i) {
if (i % 2 == 1) {
try {
Thread.sleep(1000);
System.out.println(" OddClass " + i);
i = i + 1;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
}
OUTPUT will be :-
EvenClass 0
OddClass 1
EvenClass 2
OddClass 3
EvenClass 4
OddClass 5
EvenClass 6
OddClass 7
EvenClass 8
OddClass 9
Upvotes: 0
Reputation: 123
public class ThreadEvenOdd {
static int cnt=0;
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized(this) {
while(cnt<101) {
if(cnt%2==0) {
System.out.print(cnt+" ");
cnt++;
}
notifyAll();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized(this) {
while(cnt<101) {
if(cnt%2==1) {
System.out.print(cnt+" ");
cnt++;
}
notifyAll();
}
}
}
});
t1.start();
t2.start();
}
}
Upvotes: 0
Reputation: 781
public class Solution {
static class NumberGenerator{
private static volatile boolean printEvenNumber = false;
public void printEvenNumber(int i) {
synchronized (this) {
if(!printEvenNumber) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i);
printEvenNumber = !printEvenNumber;
notify();
}
}
public void printOddNumber(int i ) {
synchronized (this) {
if(printEvenNumber) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(i);
printEvenNumber = !printEvenNumber;
notify();
}
}
}
static class OddNumberGenerator implements Runnable{
private NumberGenerator numberGenerator;
public OddNumberGenerator(NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}
@Override
public void run() {
for(int i = 1; i <100; i = i + 2) {
numberGenerator.printOddNumber(i);
}
}
}
static class EvenNumberGenerator implements Runnable {
private NumberGenerator numberGenerator;
public EvenNumberGenerator(NumberGenerator numberGenerator) {
this.numberGenerator = numberGenerator;
}
@Override
public void run() {
for (int i = 2; i <= 100; i = i + 2) {
numberGenerator.printEvenNumber(i);
}
}
}
public static void main(String[] args) {
NumberGenerator ng = new NumberGenerator();
OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(ng);
EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(ng);
new Thread(oddNumberGenerator).start();
new Thread(evenNumberGenerator).start();
}
}
Upvotes: -1
Reputation: 1744
Class to print odd Even number
public class PrintOddEven implements Runnable {
private int max;
private int number;
public PrintOddEven(int max_number,int number) {
max = max_number;
this.number = number;
}
@Override
public void run() {
while(number<=max)
{
if(Thread.currentThread().getName().equalsIgnoreCase("odd"))
{
try {
printOdd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try {
printEven();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public synchronized void printOdd() throws InterruptedException
{
if(number%2==0)
{
wait();
}
System.out.println(number+Thread.currentThread().getName());
number++;
notifyAll();
}
public synchronized void printEven() throws InterruptedException
{
if(number%2!=0)
{
wait();
}
System.out.println(number+Thread.currentThread().getName());
number++;
notifyAll();
}
}
Driver Program
public class OddEvenThread {
public static void main(String[] args) {
PrintOddEven printer = new PrintOddEven(10,1);
Thread thread1 = new Thread(printer,"odd");
Thread thread2 = new Thread (printer,"even");
thread1.start();
thread2.start();
}
}
Upvotes: 0
Reputation: 1424
This can be acheived using Lock and Condition :
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class EvenOddThreads {
public static void main(String[] args) throws InterruptedException {
Printer p = new Printer();
Thread oddThread = new Thread(new PrintThread(p,false),"Odd :");
Thread evenThread = new Thread(new PrintThread(p,true),"Even :");
oddThread.start();
evenThread.start();
}
}
class PrintThread implements Runnable{
Printer p;
boolean isEven = false;
PrintThread(Printer p, boolean isEven){
this.p = p;
this.isEven = isEven;
}
@Override
public void run() {
int i = (isEven==true) ? 2 : 1;
while(i < 10 ){
if(isEven){
p.printEven(i);
}else{
p.printOdd(i);
}
i=i+2;
}
}
}
class Printer{
boolean isEven = true;
Lock lock = new ReentrantLock();
Condition condEven = lock.newCondition();
Condition condOdd = lock.newCondition();
public void printEven(int no){
lock.lock();
while(isEven==true){
try {
condEven.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() +no);
isEven = true;
condOdd.signalAll();
lock.unlock();
}
public void printOdd(int no){
lock.lock();
while(isEven==false){
try {
condOdd.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() +no);
isEven = false;
condEven.signalAll();
lock.unlock();
}
}
Upvotes: 0
Reputation: 1207
You can use the following code to get the output with creating two anonymous thread classes.
package practice;
class Display {
boolean isEven = false;
synchronized public void printEven(int number) throws InterruptedException {
while (isEven)
wait();
System.out.println("Even : " + number);
isEven = true;
notify();
}
synchronized public void printOdd(int number) throws InterruptedException {
while (!isEven)
wait();
System.out.println("Odd : " + number);
isEven = false;
notify();
}
}
public class OddEven {
public static void main(String[] args) {
// TODO Auto-generated method stub
final Display disp = new Display();
new Thread() {
public void run() {
int num = 0;
for (int i = num; i <= 10; i += 2) {
try {
disp.printEven(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
int num = 1;
for (int i = num; i <= 10; i += 2) {
try {
disp.printOdd(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}
Upvotes: 0
Reputation: 1481
Found the solution. Someone looking for solution to this problem can refer :-)
public class PrintEvenOddTester {
public static void main(String... args) {
Printer print = new Printer();
Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));
Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
t1.start();
t2.start();
}
}
class TaskEvenOdd implements Runnable {
private int max;
private Printer print;
private boolean isEvenNumber;
TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
this.print = print;
this.max = max;
this.isEvenNumber = isEvenNumber;
}
@Override
public void run() {
//System.out.println("Run method");
int number = isEvenNumber == true ? 2 : 1;
while (number <= max) {
if (isEvenNumber) {
//System.out.println("Even :"+ Thread.currentThread().getName());
print.printEven(number);
//number+=2;
} else {
//System.out.println("Odd :"+ Thread.currentThread().getName());
print.printOdd(number);
// number+=2;
}
number += 2;
}
}
}
class Printer {
boolean isOdd = false;
synchronized void printEven(int number) {
while (isOdd == false) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even:" + number);
isOdd = false;
notifyAll();
}
synchronized void printOdd(int number) {
while (isOdd == true) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd:" + number);
isOdd = true;
notifyAll();
}
}
This gives output like:
Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9
Even:10
Upvotes: 55
Reputation: 1127
Working solution using single class
package com.fursa.threads;
public class PrintNumbers extends Thread {
Object lock;
PrintNumbers(Object lock) {
this.lock = lock;
}
public static void main(String ar[]) {
Object obj = new Object();
// This constructor is required for the identification of wait/notify
// communication
PrintNumbers odd = new PrintNumbers(obj);
PrintNumbers even = new PrintNumbers(obj);
odd.setName("Odd");
even.setName("Even");
even.start();
odd.start();
}
@Override
public void run() {
for(int i=0;i<=100;i++) {
synchronized (lock) {
if (Thread.currentThread().getName().equals("Even")) {
if(i % 2 == 0 ){
System.out.println(Thread.currentThread().getName() + " - "+ i);
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (i % 2 != 0 ) {
lock.notify();
}
}
if (Thread.currentThread().getName().equals("Odd")) {
if(i % 2 == 1 ){
System.out.println(Thread.currentThread().getName() + " - "+ i);
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (i % 2 != 1 ) {
lock.notify();
}
}
}
}
}
}
Upvotes: 0
Reputation: 63
package com.example;
public class MyClass {
static int mycount=0;
static Thread t;
static Thread t2;
public static void main(String[] arg)
{
t2=new Thread(new Runnable() {
@Override
public void run() {
System.out.print(mycount++ + " even \n");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(mycount>25)
System.exit(0);
run();
}
});
t=new Thread(new Runnable() {
@Override
public void run() {
System.out.print(mycount++ + " odd \n");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(mycount>26)
System.exit(0);
run();
}
});
t.start();
t2.start();
}
}
Upvotes: 0
Reputation: 326
I think the solutions being provided have unnecessarily added stuff and does not use semaphores to its full potential. Here's what my solution is.
package com.test.threads;
import java.util.concurrent.Semaphore;
public class EvenOddThreadTest {
public static int MAX = 100;
public static Integer number = new Integer(0);
//Unlocked state
public Semaphore semaphore = new Semaphore(1);
class PrinterThread extends Thread {
int start = 0;
String name;
PrinterThread(String name ,int start) {
this.start = start;
this.name = name;
}
@Override
public void run() {
try{
while(start < MAX){
// try to acquire the number of semaphore equal to your value
// and if you do not get it then wait for it.
semaphore.acquire(start);
System.out.println(name + " : " + start);
// prepare for the next iteration.
start+=2;
// release one less than what you need to print in the next iteration.
// This will release the other thread which is waiting to print the next number.
semaphore.release(start-1);
}
} catch(InterruptedException e){
}
}
}
public static void main(String args[]) {
EvenOddThreadTest test = new EvenOddThreadTest();
PrinterThread a = test.new PrinterThread("Even",1);
PrinterThread b = test.new PrinterThread("Odd", 2);
try {
a.start();
b.start();
} catch (Exception e) {
}
}
}
Upvotes: 0