Skip to content

Instantly share code, notes, and snippets.

@yujin8920
Created January 24, 2016 09:05
Show Gist options
  • Save yujin8920/7ebbe40adaf0b9aec74e to your computer and use it in GitHub Desktop.
Save yujin8920/7ebbe40adaf0b9aec74e to your computer and use it in GitHub Desktop.
NotifyTest
public class NotifyTest {
private final String flag[] = {"true"};
class NotifyThread extends Thread {
public NotifyThread(String name) {
super(name);
}
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (flag) {
flag[0] = "false";
flag.notifyAll();
}
}
}
class WaitThread extends Thread {
public WaitThread(String name) {
super(name);
}
public void run() {
synchronized(flag) {
while(!flag[0].equals("false")) {
System.out.println(getName()+ " starts waiting!");
long waitTime = System.currentTimeMillis();
try {
flag.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
waitTime = System.currentTimeMillis() - waitTime;
System.out.println("wait time: " + waitTime);
}
System.out.println(getName() + "end waiting!");
}
}
}
public static void main(String [] args) throws InterruptedException{
System.out.println("Main thread start run!");
NotifyTest notifyTest = new NotifyTest();
NotifyThread notifyThread = notifyTest.new NotifyThread("notify01");
WaitThread waitThread1 = notifyTest.new WaitThread("wait01");
WaitThread waitThread2 = notifyTest.new WaitThread("wait02");
WaitThread waitThread3 = notifyTest.new WaitThread("wait03");
notifyThread.start();
waitThread1.start();
waitThread2.start();
waitThread3.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment