【詳解】Java併發之確保掛起設計模式

分析

在Tomcat中的例子

Request -> Tomcat httpServer  -> doing
.................
Request -> Tomcat httpServer  -> Queue wait -> doing

需求
​ 一個線程正在做一個非常關鍵的任務,這時,有一個其他的線程讓當前線程做其他的事情,當前線程只有完成當前的任務才能做其他的任務。

解決方法

使用隊列將其他需要工作的線程保存,然後在未來需要時,繼續取隊列中獲取任務,然後執行。

public class ServerThread extends Thread {
    private final RequestQueue queue;
    private final Random random;

    public ServerThread(RequestQueue queue) {
        this.queue = queue;
        random = new Random(System.currentTimeMillis());
    }

    @Override
    public void run() {
        while (!Thread.interrupted()){
            Request request = queue.getRequest();
            if (request == null){
                break;
            }
            System.out.println("server ->"+request.getValue());
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                break;
            }
        }
    }
}
public class RequestQueue {

    private final LinkedList<Request> queue = new LinkedList<>();


    /**
     * 放任務
     *
     * @param request 請求任務
     */
    public void putRequest(Request request) {
        synchronized (queue) {
            queue.addLast(request);
            queue.notifyAll();
        }
    }


    /**
     * 取任務
     *
     * @return
     */
    public Request getRequest() {
        synchronized (queue) {
            while (!(queue.size() > 0)) {
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    return null;
                }
            }
            if (Thread.interrupted()){
                return null;
            }
            return queue.removeFirst();
        }
    }
}
public class Request {

    final String value;

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

    public String getValue() {
        return value;
    }
}
public class Test {

    public static void main(String[] args) throws InterruptedException {
        final RequestQueue queue = new RequestQueue();

        new ClientThread(queue,"Alex").start();

        ServerThread serverThread = new ServerThread(queue);
        serverThread.start();


        Thread.sleep(1000);
        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        threadGroup.interrupt();

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章