Created
July 10, 2012 11:38
-
-
Save binarytemple/3082807 to your computer and use it in GitHub Desktop.
Java Wait Nofify Example
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
import java.util.ArrayList; | |
import java.util.List; | |
import static java.lang.String.format; | |
public class NotifyTest { | |
static final class NotifiableRunner extends Thread { | |
private final int id; | |
// The mutex upon which this thread will wait and respond to notify | |
private final Lock lock; | |
// Variable that determines whether the Thread should continue running | |
private boolean keepalive = true; | |
// Switch to false and the run() method will terminate | |
public NotifiableRunner(int id, Lock lock) { | |
super(); | |
this.id = id; | |
this.lock = lock; | |
} | |
public void makewait() { | |
synchronized (lock) { | |
try { | |
lock.wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
@Override | |
public void run() { | |
while (isKeepalive()) { | |
makewait(); | |
System.out.println(id); | |
} | |
} | |
public boolean isKeepalive() { | |
return keepalive; | |
} | |
public void setKeepalive(boolean keepalive) { | |
this.keepalive = keepalive; | |
} | |
} | |
private static final class Lock { | |
} | |
public static void main(String[] args) { | |
final Lock lock = new Lock(); | |
List<NotifiableRunner> list = new ArrayList<NotifyTest.NotifiableRunner>(); | |
for (int i = 0; i < 4; i++) { | |
System.err.println(format("creating %d", i)); | |
NotifiableRunner e = new NotifiableRunner(i, lock); | |
e.start(); | |
list.add(e); | |
} | |
System.out.println("created threads"); | |
sleepytime(1000); | |
System.out.println("notifying threads"); | |
notifyThreads(lock); | |
sleepytime(1000); | |
notifyThreads(lock); | |
sleepytime(1000); | |
System.out.println("finishing"); | |
terminateThreads(lock, list); | |
} | |
private static void terminateThreads(final Lock lock, | |
List<NotifiableRunner> list) { | |
for (NotifiableRunner nr : list) { | |
nr.setKeepalive(false); | |
} | |
synchronized (lock) { | |
lock.notifyAll(); | |
} | |
} | |
private static void notifyThreads(final Lock lock) { | |
for (int i = 0; i < 4; i++) { | |
synchronized (lock) { | |
System.err.println(format("notifying %d", i)); | |
lock.notify(); | |
} | |
} | |
} | |
private static void sleepytime(int millis) { | |
try { | |
Thread.sleep(millis); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment