手机版
你好,游客 登录 注册
背景:
阅读新闻

Java多线程模式

[日期:2013-08-15] 来源:Linux社区  作者:shenzhen_liubin [字体:大 中 小]

Active Object Pattern

Active Object Pattern其实可以看作是多个多线程模式和多个设计模式组合成的一种更高级的模式,里面多个对象各司其职,共同协作。Active Object Pattern里面使用到了Producer-Consumer Pattern、Thread-Per-Message Pattern、Future Pattern和设计模式的Proxy Pattern、Command Pattern等。

Server端代码:

public interface ActiveObject {

    public Result makeString(int count, char fillchar);

    public void displayString(String string);
}


public class Proxy implements ActiveObject {

    private SchedulerThread scheduler;

    private Servant        servant;

    public Proxy(SchedulerThread scheduler, Servant servant) {
        this.scheduler = scheduler;
        this.servant = servant;
    }

    @Override
    public Result makeString(int count, char fillchar) {
        FutureResult future = new FutureResult();
        MakeStringRequest request = new MakeStringRequest(servant, future, count, fillchar);
        this.scheduler.invoke(request);
        return future;
    }

    @Override
    public void displayString(String string) {
        DisplayStringRequest request = new DisplayStringRequest(servant, string);
        this.scheduler.invoke(request);
    }
}

public class Servant implements ActiveObject {

    @Override
    public Result makeString(int count, char fillchar) {
        char[] buffer = new char[count];
        for (int i = 0; i < count; i++) {
            buffer[i] = fillchar;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }
        }

        RealResult result = new RealResult(String.valueOf(buffer));
        return result;
    }

    @Override
    public void displayString(String string) {
        System.out.println("displayString( " + string + " )");
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
        }
    }
}

public interface Result {

    public String getResultValue();
}


public class FutureResult implements Result {

    private Result  result;

    private boolean isReady = false;

    public synchronized void setResult(Result result) {
        if (isReady) {
            return;
        }
        this.result = result;
        this.isReady = true;
        notifyAll();
    }

    @Override
    public synchronized String getResultValue() {
        while (!isReady) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        return result.getResultValue();
    }

}

public class RealResult implements Result {

    private String resultValue;

    public RealResult(String resultValue) {
        this.resultValue = resultValue;
    }

    @Override
    public String getResultValue() {
        return this.resultValue;
    }
}


public abstract class MethodRequest {

    protected final Servant      servant;

    protected final FutureResult future;

    public MethodRequest(Servant servant, FutureResult future) {
        this.servant = servant;
        this.future = future;
    }

    public abstract void execute();

}


public class MakeStringRequest extends MethodRequest {

    private int  count;

    private char fillchar;

    public MakeStringRequest(Servant servant, FutureResult future, int count, char fillchar) {
        super(servant, future);
        this.count = count;
        this.fillchar = fillchar;
    }

    @Override
    public void execute() {
        Result result = this.servant.makeString(count, fillchar);
        future.setResult(result);
    }
}


public class DisplayStringRequest extends MethodRequest {

    private String string;

    public DisplayStringRequest(Servant servant, String string) {
        super(servant, null);
        this.string = string;
    }

    @Override
    public void execute() {
        this.servant.displayString(string);
    }
}

public class SchedulerThread extends Thread {

    private ActivationQueue queue = new ActivationQueue();

    public void invoke(MethodRequest request) {
        this.queue.putRequest(request);
    }

    @Override
    public void run() {
        while (true) {
            this.queue.takeRequest().execute();
        }
    }
}

package activeobject.server;

import Java.util.LinkedList;

public class ActivationQueue {

    private final LinkedList<MethodRequest> requestQueue = new LinkedList<MethodRequest>();

    private final int                      queueSize    = 100;

    public synchronized void putRequest(MethodRequest request) {
        while (this.requestQueue.size() >= queueSize) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        this.requestQueue.addLast(request);
        notifyAll();
    }

    public synchronized MethodRequest takeRequest() {
        while (this.requestQueue.size() == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }

        MethodRequest request = this.requestQueue.removeFirst();
        notifyAll();
        return request;
    }
}

public class ActiveObjectFactory {

    public static ActiveObject createActiveObjcet() {
        Servant servant = new Servant();

        SchedulerThread scheduler = new SchedulerThread();

        Proxy proxy = new Proxy(scheduler, servant);

        scheduler.start();

        return proxy;
    }
}

UML如下图:

客户端代码:

import activeobject.server.ActiveObject;

public class DisplayClientThread extends Thread {

    private ActiveObject activeObj;

    public DisplayClientThread(String name, ActiveObject activeObj) {
        super(name);
        this.activeObj = activeObj;
    }

    @Override
    public void run() {
        int i = 0;
        while (true) {
            i++;
            String string = getName() + " No." + i;
            activeObj.displayString(string);
        }
    }
}

import activeobject.server.ActiveObject;
import activeobject.server.Result;

public class MakerClientThread extends Thread {

    private final ActiveObject activeObj;

    private final char        fillchar;

    public MakerClientThread(String name, ActiveObject activeObj) {
        super(name);
        this.activeObj = activeObj;
        this.fillchar = name.charAt(0);
    }

    @Override
    public void run() {
        int i = 0;
        while (true) {
            i++;
            Result result = activeObj.makeString(i, fillchar);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }

            String resultValue = result.getResultValue();
            System.out.println(Thread.currentThread().getName() + ":value = " + resultValue);
        }

    }
}

import activeobject.server.ActiveObject;
import activeobject.server.ActiveObjectFactory;

public class Main {

    public static void main(String[] args) {
        ActiveObject activeObj = ActiveObjectFactory.createActiveObjcet();
        new MakerClientThread("Alice", activeObj).start();
        new MakerClientThread("Bobby", activeObj).start();
        new DisplayClientThread("Chris", activeObj).start();
    }
}

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款