1.示例

  • Host.java

package com.gc.pattern;

public final class Host {

    private final Helper m_helper = new Helper();
    public Host(){
        }
    public void request(final int count, final char c) {
        System.out.println(" request(" + count + " , " + c + ") Begin ");
        Thread t_tempThread = new Thread(){
                public void run(){
                m_helper.handle(count, c);
            }
        };
        t_tempThread.start();
        System.out.println(" request(" + count + " , " + c + ") End ");
    }
}

  • Helper.java

package com.gc.pattern;

public final class Helper{
    public Helper(){
        }
    public void handle(int count,char c){
        System.out.println(" handle(" + count + " , " + c + " ) Begin ");
        for (int i = 0 ; i < count ; i++ ){
            slowly(1000);
            System.out.print(c);
        }
        System.out.println("");
        System.out.println(" handle(" + count + " , " + c + " ) End ");
        
    }
    private void slowly(long sleepTime){
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e){
            // TODO: handle exception
        }
    }

}

  • ThreadPerMessaageTest.java

package com.gc.pattern;
public final class ThreadPerMessageTest{
       public ThreadPerMessageTest(){
            }
        
       public static void main(String[] args){
          System.out.println("main Begin");
          Host t_host = new Host();
          t_host.request(10,'c');
          t_host.request(12,'b');
          t_host.request(8, 'a');
          System.out.println("main End");
        }
}

2.观念

    简单的说,Thread Per Message 模式是在某个请求发生时,新增一个线程来处理该请求,主线程继续往下执行。像文档载入,搜寻,字串转换之类需要一些时间来执行时,使用该模式可以提高主线程(界面)的响应。例如:

menuOpenFile.addActionListener(
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Thread(new Runnable(){
                public void run() {
                    openFile();
                }
            }).start();
        }
    }
 );

posted on 2015-04-13 22:29  小光zfg  阅读(139)  评论(0)    收藏  举报