Last active
December 27, 2023 10:04
-
-
Save hocyadav/5ad0a32002dc52820c9a13e4301ae67a to your computer and use it in GitHub Desktop.
print even and odd number using 2 thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
* @author Hariom Yadav | |
* @since 17-Nov-2023 | |
*/ | |
public class ThreadEvenOddPrint { | |
/** | |
* thread 1 will print even and other will print odd | |
* approach : take share resources atomic int and using inside both runner | |
* NOTE : approach same as producer and consumer pattern, they are accessing common counter resource `AtomicInteger` | |
*/ | |
@Test | |
public void foo(){ | |
AtomicInteger atomic = new AtomicInteger(0); | |
Runnable even = () -> { | |
while (true) { | |
sleep(1000); | |
if (atomic.get() % 2 == 0) { | |
System.out.println("Even = " + atomic.getAndIncrement()); | |
} | |
} | |
}; | |
Runnable odd = () -> { | |
while (true) { | |
sleep(1000); | |
if (atomic.get() % 2 != 0) { | |
System.out.println("Odd = " + atomic.getAndIncrement()); | |
} | |
} | |
}; | |
new Thread(even).start(); | |
new Thread(odd).start(); | |
Thread.sleep(400000); | |
} | |
private static void sleep(int millis) { | |
try { | |
Thread.sleep(millis); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
approach 2, same as above but refactored logic to a class : https://gist.github.com/hocyadav/232a3129a5e0a04c215d197c908a1ac8#file-threadevenoddprint-java
producer-consumer pattern impl using 2 thread : https://gist.github.com/hocyadav/58586e209215cca3ce88c80d7c0d1dc8
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output :