Java所有的類(lèi)都具有線程的潛力,Java賦予的每個(gè)對(duì)象一個(gè)鎖,在計(jì)算機(jī)內(nèi)部工作在同一時(shí)間,只有一個(gè)對(duì)象可以持有鎖,也就是說(shuō)程序在同一時(shí)間只有一個(gè)程序可以運(yùn)行,這里我把對(duì)象比作是一個(gè)小的程序。而多處理器,那么就另當(dāng)別論了。
在這里我們首先學(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