Guarded Suspension Pattern

package com.albert.thread;

import java.util.LinkedList;
import java.util.Random;


class Request
{
    private final String name;
    public Request(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return name;
    }
    public String toString()
    {
        return "[Request "+name+"]";
    }
}

class RequestQueue
{
    private final LinkedList queue = new LinkedList();
    
    public synchronized Request getRequest()

    {

      //Guarded Condition

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

        return (Request) this.queue.removeFirst();
    }
    public synchronized void putRequest(Request req)
    {
        queue.addLast(req);
        this.notifyAll();
    }
}
class ClientThread extends Thread
{
    private Random random;
    private RequestQueue requestQueue;
    
    public ClientThread(RequestQueue reqQueue,String name,long seed)
    {
        super(name);
        this.requestQueue = reqQueue;
        this.random = new Random(seed);
    }
    public void run()
    {
        for(int i=0;i<1000;i++)
        {
            Request req = new Request("No."+i);
            System.out.println(Thread.currentThread().getName()+" requests :"+req);
            this.requestQueue.putRequest(req);
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class ServerThread extends Thread
{
    private Random random;
    private RequestQueue requestQueue;
    public ServerThread(RequestQueue queue,String name,long seed)
    {
        super(name);
        this.requestQueue = queue;
        this.random = new Random(seed);
    }
    public void run()
    {
        for(int i=0;i<1000;i++)
        {
            Request req = this.requestQueue.getRequest();
            System.out.println(Thread.currentThread().getName()+" handles "+req);
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class MyThread {


    private static final long CALL_COUNT=100000L;
    
    /**
     * @param args
     */
    public static void main(String[] args) {

        RequestQueue requestQueue = new RequestQueue();
        new ClientThread(requestQueue,"Alice",3333333L).start();
        new ServerThread(requestQueue,"Bobby",555555L).start();
    }
}

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