Skip to content

Instantly share code, notes, and snippets.

@peter-lawrey
Created April 21, 2016 19:15
Show Gist options
  • Save peter-lawrey/70c3313ef7d76f468a69e059d5d0f012 to your computer and use it in GitHub Desktop.
Save peter-lawrey/70c3313ef7d76f468a69e059d5d0f012 to your computer and use it in GitHub Desktop.
public class PingPongMain {
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
try {
synchronized ("bb") {
while (true) {
"bb".wait();
"bb".notifyAll();
System.out.println("b");
}
}
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}).start();
Thread.sleep(100);
setString("bb", 'c', 'C');
new Thread(() -> {
try {
// change "cC" to "cc" and this program prints nothing.
synchronized ("cC") {
while (true) {
"cC".notifyAll();
"cC".wait();
System.out.println("c");
}
}
} catch (InterruptedException e) {
throw new AssertionError(e);
}
}).start();
}
public static void setString(String s, char... chars) {
try {
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
value.set(s, chars);
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
@peter-lawrey
Copy link
Author

This prints

b
c
b
c
b
c

but change "cC" to "cc" and it prints nothing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment