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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值