在這里我們首先學(xué)習(xí)一下公共方法wait,notify,notifyAll。
wait方法可以使在當(dāng)前線程的對(duì)象等待,直到別的線程調(diào)用此對(duì)象的notify或notifyAll方法(注意:調(diào)用的是此對(duì)象的notify和notifyAll),并且當(dāng)前運(yùn)行的線程必須具有此對(duì)象的對(duì)象監(jiān)視器
package com.abin.lee.thread.thread;
public class CarryTask extends Thread {
public void run() {
try {
synchronized (this) {
Thread t = Thread.currentThread();
System.out.println(t.getId() + t.getName() + ":task start, wait for notify...");
this.wait();
System.out.println(t.getId() + t.getName() + ":task continue...");
}
} catch (InterruptedException ex) {
System.out.println(CarryTask.class.getName());
}
}
}
package com.abin.lee.thread.thread;
public class CarryWait {
public static void main(String[] args) throws InterruptedException {
CarryTask task = new CarryTask();
Thread t = Thread.currentThread();
System.out.println(t.getId() + t.getName() + ":task start...");
task.start();
Thread.sleep(2000);
synchronized (task) {
System.out.println("id="+Thread.currentThread().getId()+",Name="+Thread.currentThread().getName()+",task="+task+",notify");
task.notify();
}
}
}
http://www.iteye.com/topic/1124814