Skip to content

Instantly share code, notes, and snippets.

@jerrypnz
Created October 26, 2012 06:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerrypnz/3957225 to your computer and use it in GitHub Desktop.
Save jerrypnz/3957225 to your computer and use it in GitHub Desktop.
public class PrintAB {
// The code below would print overlapped A and B sequences like:
// ...
// A
// A
// B
// B
// ...
//
// Please add multi-threading protection code to make sure that
// As and Bs are printed in the order of:
// ...
// A
// B
// A
// B
// ...
private static ReentrantLock lock = new ReentrantLock();
private static void printA() {
lock.lock();
System.out.println("A");
}
private static void printB() {
System.out.println("B");
lock.unlock();
}
// DO NOT touch the code below
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
printA();
printB();
}
}
}).start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment