Posted on 2009-06-02 20:19
啥都寫點 閱讀(186)
評論(0) 編輯 收藏 所屬分類:
J2SE
關鍵技術:
- 在synchronized代碼塊中使用wait方法,能夠使當前線程進入等待狀態,并釋放當前線程擁有的對象鎖。
- 在synchronized代碼塊中使用notify或者notifyAll方法,當前線程釋放對象鎖,并喚醒其他正在等待該對象鎖的線程。當有多個線程都在等待該對象鎖時,由Java虛擬機決定被喚醒的等待線程。
package book.thread;
import java.util.Vector;
/**
* 線程間的協作
*/
public class WaitNotify {
/**
* 打印信息的類,是一個線程。
*/
static class Printer extends Thread{
Vector task = new Vector();
boolean running = false;
public void start(){
this.running = true;
super.start();
}
public void run(){
try {
System.out.println("Printer begin!");
while (running){
synchronized(this) {
while ((task.size() == 0) && running){
//如果任務列表為空,而且線程還允許運行,則等待任務
System.out.println("wait begin!");
//該線程進入等待狀態,直到被其他線程喚醒
wait();
System.out.println("wait end!");
}
}
if (running){
System.out.println("print the task: " + task.remove(0));
}
}
System.out.println("Printer end!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 添加待打印的任務
*/
public void addTask(String str){
synchronized (this){
this.task.add(str);
//喚醒其他等待的線程
System.out.println("addTask notify!");
notify();
//notifyAll();
}
}
/**
* 停止線程
*/
public void stopPrinter(){
this.running = false;
synchronized (this){
//喚醒其他等待的線程
System.out.println("stopPrinter notify!");
notify();
}
}
}
public static void main(String[] args) {
Printer printer = new Printer();
//啟動打印線程
printer.start();
//添加任務
try {
Thread.sleep(200);
for (int i=0; i<5; i++){
//休眠200毫秒
Thread.sleep(200);
printer.addTask("The task " + i);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
printer.stopPrinter();
}
}
--
學海無涯