Last active
April 3, 2017 17:36
-
-
Save liweinan/63b7bf4410250fd2704155f9d0d83d11 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* @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