Last active
November 7, 2021 06:52
-
-
Save Noman5237/efb07a0e9d85452d813783bc728954ed to your computer and use it in GitHub Desktop.
Print in Order Multithreaded
This file contains hidden or 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; | |
| class Foo { | |
| public void first() { | |
| System.out.println("first"); | |
| } | |
| public void second() { | |
| System.out.println("second"); | |
| } | |
| public void third() { | |
| System.out.println("third"); | |
| } | |
| } | |
| public class PrintInOrder { | |
| public static void main(String[] args) { | |
| AtomicInteger current = new AtomicInteger(0); | |
| Foo foo = new Foo(); | |
| Thread first = new Thread(() -> { | |
| while (current.intValue() != 0) ; | |
| foo.first(); | |
| current.incrementAndGet(); | |
| }); | |
| Thread second = new Thread(() -> { | |
| while (current.intValue() != 1) ; | |
| foo.second(); | |
| current.incrementAndGet(); | |
| }); | |
| Thread third = new Thread(() -> { | |
| while (current.intValue() != 2) ; | |
| foo.third(); | |
| current.incrementAndGet(); | |
| }); | |
| first.start(); | |
| second.start(); | |
| third.start(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment