Skip to content

Instantly share code, notes, and snippets.

@hocyadav
Last active December 27, 2023 10:04
Show Gist options
  • Save hocyadav/5ad0a32002dc52820c9a13e4301ae67a to your computer and use it in GitHub Desktop.
Save hocyadav/5ad0a32002dc52820c9a13e4301ae67a to your computer and use it in GitHub Desktop.
print even and odd number using 2 thread
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);
}
}
}
@hocyadav
Copy link
Author

@hocyadav
Copy link
Author

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