Skip to content

Instantly share code, notes, and snippets.

@Noman5237
Last active November 7, 2021 06:52
Show Gist options
  • Select an option

  • Save Noman5237/efb07a0e9d85452d813783bc728954ed to your computer and use it in GitHub Desktop.

Select an option

Save Noman5237/efb07a0e9d85452d813783bc728954ed to your computer and use it in GitHub Desktop.
Print in Order Multithreaded
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