Created
December 27, 2023 09:40
-
-
Save hocyadav/232a3129a5e0a04c215d197c908a1ac8 to your computer and use it in GitHub Desktop.
Even oddd print 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 lombok.SneakyThrows; | |
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
* @author Hariom Yadav | |
* @since 27-Dec-2023 | |
*/ | |
public class EvenRunner implements Runnable { | |
AtomicInteger atomic; | |
public EvenRunner(AtomicInteger atomic) { | |
this.atomic = atomic; | |
} | |
@SneakyThrows | |
@Override | |
public void run() { | |
while (true) { | |
Thread.sleep(1000); | |
if (atomic.get() % 2 == 0) { | |
System.out.println("Even = " + atomic.getAndIncrement()); | |
} | |
} | |
} | |
} |
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 lombok.SneakyThrows; | |
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
* @author Hariom Yadav | |
* @since 27-Dec-2023 | |
*/ | |
public class OddRunner implements Runnable{ | |
AtomicInteger atomic; | |
public OddRunner(AtomicInteger atomic) { | |
this.atomic = atomic; | |
} | |
@SneakyThrows | |
@Override | |
public void run() { | |
while (true) { | |
Thread.sleep(1000); | |
if (atomic.get() % 2 != 0) { | |
System.out.println("Odd = " + atomic.getAndIncrement()); | |
} | |
} | |
} | |
} |
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 lombok.SneakyThrows; | |
import org.jetbrains.annotations.NotNull; | |
import org.junit.jupiter.api.Test; | |
import java.util.concurrent.atomic.AtomicInteger; | |
/** | |
* @author Hariom Yadav | |
* @since 17-Nov-2023 | |
*/ | |
public class ThreadEvenOddPrint { | |
/** | |
* approach : take share resources atomic int | |
*/ | |
@SneakyThrows | |
@Test | |
public void foo(){ | |
AtomicInteger atomic = new AtomicInteger(0); | |
Runnable even = new EvenRunner(atomic); | |
Runnable odd = new OddRunner(atomic); | |
new Thread(even).start(); | |
new Thread(odd ).start(); | |
Thread.sleep(400000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment