二.多线程设计模式篇-2.6 Guarded Suspension设计模式

1.概念

如果执行现在的处理会造成问题,就让执行处理的线程等待。这种模式通过让线程等待来保证实例的安全性

2.核心思想

当且仅当服务进程准备好时,才提供服务。设想一种场景,服务器可能会在很短时间内承受大量的客户端请求,客户端请求的数量可能超过服务器本身的即时处理能力,而服务端程序又不能丢弃任何一个客户请求。此时,最佳的处理方案莫过于让客户端请求进行排队,由服务端程序一个接一个处理。这样,既保证了所有的客户端请求均不丢失,同时也避免了服务器由于同时处理太多请求而崩溃。

3.例子

  • Request
public class Request {
    private String value;

    public Request(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}
  • RequestQueue
public class RequestQueue {
    private LinkedList queue= new LinkedList<>();

    public synchronized void addRequest(Request request){
        queue.add(request);
        notifyAll();
    }

    public synchronized Request getRequest()  {
        while (queue.size() <=0 ){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return queue.remove();
    }
}

  • ClientThread
public class ClientThread extends Thread {
    private  RequestQueue queue;
    private  String sendValue;

    public ClientThread( String name, RequestQueue queue, String sendValue) {
        super(name);
        this.queue = queue;
        this.sendValue = sendValue;
    }

    @Override
    public void run() {
        for (int i = 0 ; i< 10; i++){
            Request request = new Request(this.sendValue);
            queue.addRequest(request);
            System.out.println("Request thread: " + currentThread().getName() + "---->value: " + this.sendValue);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
  • ServerThread
public class ServerThread extends Thread {
    private RequestQueue requestQueue;

    public ServerThread(String name, RequestQueue requestQueue) {
        super(name);
        this.requestQueue = requestQueue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Request request = requestQueue.getRequest();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Sever thread: " + currentThread().getName() + "<-------value: " + request.getValue());
        }
    }
}

你可能感兴趣的:(#,多线程)