Skip to content

Instantly share code, notes, and snippets.

@liweinan
Last active April 3, 2017 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save liweinan/63b7bf4410250fd2704155f9d0d83d11 to your computer and use it in GitHub Desktop.
Save liweinan/63b7bf4410250fd2704155f9d0d83d11 to your computer and use it in GitHub Desktop.
/**
* @author <a href="mailto:l.weinan@gmail.com">Weinan Li</a>
*/
public class Lock {
volatile boolean waiting = true;
public void test() {
new Thread(new Runnable() {
public void run() {
while (waiting) ;
System.out.println("Thread 1 finished.");
}
}).start();
new Thread(new Runnable() {
public void run() {
// Sleep for a bit so that thread 1 has a chance to start
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
System.out.println("Thread 2 shutdown...");
waiting = false;
}
}).start();
}
public static void main(String[] args) {
new Lock().test();
}
}
---
import java.util.concurrent.CountDownLatch;
/**
* @author <a href="mailto:l.weinan@gmail.com">Weinan Li</a>
*/
public class Volatile {
volatile boolean waiting = true;
CountDownLatch lock = new CountDownLatch(1);
public void test() {
new Thread(new Runnable() {
public void run() {
try {
lock.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 finished.");
}
}).start();
new Thread(new Runnable() {
public void run() {
// Sleep for a bit so that thread 1 has a chance to start
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
System.out.println("Thread 2 shutdown...");
lock.countDown();
}
}).start();
}
public static void main(String[] args) {
new Volatile().test();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment