keep moving!

We must not cease from exploration. And the end of all our exploring will be to arrive where we began and to know the place for the first time.
随笔 - 37, 文章 - 2, 评论 - 3, 引用 - 0
数据加载中……

Design Pattern: Thread-Per-Message 模式

Thread-Per-Message模式是一個很簡單但很常應用的模式,尤其是在GUI程式中,我們舉個例子,當您設計一個文件編輯器時,您可能像這樣註冊一個開啟檔案的事件處理:
 menuOpenFile.addActionListener(
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            openFile();
        }
    }
 );
 

openFile()方法中主要是開啟檔案、一行一行讀檔案文字並設定文字至文字區域中,這樣設計基本上沒有什麼問題,例如果您的文件內容很長,在讀檔必須花費一些時間時,您會發現在檔案讀取完畢前,您的視窗會有明顯的停頓現象。
 menuOpenFile.addActionListener(
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Thread(new Runnable(){
                public void run() {
                    openFile();
                }
            }).start();
        }
    }
 );
 
在事件發生之後,您將檔案處理的動作交由一個執行緒去執行,而事件處理執行緒直接回到回應事件的狀態,如此即可解決視窗在載入檔案時的停頓。

簡單的說,Thread-Per-Message模式是在某個請求發生時,新增一個執行緒來執行該請求,而主執行緒繼續往下執行,除了上面的載入檔案例子之外,像是進行搜尋、字串轉換之類需要一些時間來執行的工作時,使用Thread-Per-Message模式都可以提高主執行緒(界面)的回應性。



张金鹏 2007-04-17 10:56 发表评论

文章来源:http://www.blogjava.net/jesson2005/articles/111198.html

posted on 2008-09-07 11:06 大石头 阅读(189) 评论(0)  编辑  收藏 所属分类: 多线程


只有注册用户登录后才能发表评论。


网站导航: