《图解Java多线程设计模式》笔记 Guarded Suspension模式

Guarded Suspension模式–等我准备好哦。例如:快递员敲你家门,你还在衣衫不整的睡觉。你会大声应答到:等我准备好哦。此时快递员会一直在门外等你准备好。

  1. Guarded是被守护、被保护的意思,Suspension是暂停的意思。这两个单词很好的阐述了该模式的特点。该模式是通过线程的等待来保证实例的安全性。

  2. 应用场景:一个线程ClientThread会将请求Request的实例通过队列RequestQueue传递给另一个线程ServerThread。
    1)Request类:

public class Request {

	private String name;
	
	public Request(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
	
	public String toString(){
		return "request name is " + name;
	}
}

2)RequestQueue类:

public class RequestQueue {

	private final LinkedList<Request> queue = new LinkedList<Request>();
	
	//取任务
	public synchronized Request getRequest(){
		
		while(queue.peek() == null){
			try {
				this.wait();  //等待  1.会释放对象锁 2.进入线程等待队列(notify可唤醒)
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return queue.remove();
	}
	
	
	//添加任务
	public synchronized void putRequest(Request request){
		
		queue.offer(request);
		this.notifyAll();   //通知
	}
}

3)ClientThread类:

public class ClientThread extends Thread{

	private final RequestQueue queue;  //注意:对象用final,是不能改变其引用值
	
	private final Random random;
	
	public ClientThread(String name , RequestQueue queue , long seed){
		super(name);
		this.queue = queue;
		this.random = new Random(seed);
	}
	
	@Override
	public void run() {
		
		for(int i=0 ; i<1000 ; i++){
			Request request = new Request("task [" + i + "]");
			int time = random.nextInt(1000);
			try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("begin put request " + "task [" + i + "]");
			queue.putRequest(request);
		}
	}
}

4)ServerThread类:

public class ServerThread extends Thread{

	private final RequestQueue queue;
	
	private final Random random;
	
	public ServerThread(String name , RequestQueue queue , long seed){
		super(name);
		this.queue = queue;
		this.random = new Random(seed);
	}
	
	@Override
	public void run() {
		
		for(int i=0 ; i<1000 ; i++){
			try {
				Thread.sleep(random.nextInt(1000));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Request request = queue.getRequest();
			System.out.println("=======get request " + request.getName());
		}
	}
}

5)Main类:

public class Main {

	public static void main(String[] args) {
		RequestQueue queue = new RequestQueue();
		new ClientThread("client" , queue , 234L).start();
		new ServerThread("server" , queue , 678L).start();
	}
}
  1. 上面代码重点之处是RequestQueue。通过synchronized来保证线程互斥访问资源queue。其实也可以通过在ClientThread和ServerThread中共享一个锁来完成线程互斥,也可以防止造成queue的数据竞争。为什么要采用第一种方案?原因如下:
    1)复用:把线程互斥代码(wait、notify)封装在RequestQueue类中,是一个线程安全队列。则使用RequestQueue的其他类无须关注线程问题。当其他工程需要一个线程安全队列时,可以直接拿这个类复用。
    2)降低代码复杂度:例如我们常用的数据库为了保证数据安全是读写互斥的。所以应用层开发人员调用数据库api时,一般情况是不用关心线程互斥造成数据竞争问题的。如上面RequestQueue保证线程安全后,编写ClientThread和ServerThread是不用关心线程安全问题。

  2. 队列java.util.Queue是FIFO(First In First Out)先进先出。

  3. ArrayList与LinkedList区别:
    1)都是非线程安全类。
    2)ArrayList和LinkedList都实现了java.util.List接口。所以两个对象都实现了get(int index),remove(int index)和add(int index , E element)方法。
    3)LinkedList现实了java.util.Queue接口,所以有FIFO特性的方法。而ArrayList没有。
    4)ArrayList优点是读操作,而LinkedList优点是新增删除操作。

  4. LinkedList 常用函数:
    1)remove()移除队列的第一个元素,并返回该元素。
    2)offer(E element)将元素添加到队列末尾。
    3)E peek()返回第一个元素,但不移除元素。

  5. Guarded Suspension守护条件伪代码:
    while(守护条件逻辑非){
    使用wait进行等待;
    }
    执行目标处理;

  6. Guarded Suspension模式就像是“多线程版本的if”。

  7. GuardedObject(被守护的对象):
    GuardedObject角色是一个持有被守护的方法(guardedMethod)的类。当线程执行guardedMethod方法时,若守护条件成立,则可立即执行;当守护条件不成立时,就要进行等待。直到GuardedObject角色的状态不同而发生改变。

  8. guardedMethod通过while语句和wait方法来实现,stateChangingMethod则通过notify/notifyAll方法来实现。

  9. wait一段时候后如果想要中断,可以在wait中指定参数wait(timeout)。

  10. java.util.concurrent.LinkedBlockingQueue实现了Guarded Suspension模式。实现了接口java.util.concurrent.BlockingQueue接口。

public class RequestQueue {

	private final BlockingQueue<Request> queue = new LinkedBlockingQueue<>();
	
	public Request getRequest(){
		Request req = null;
		try {
			req = queue.take();  //当队列为空时,若调用take方法便会进行wait
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return req;
	}
	
	public void putRequest(Request req){
		try {
			queue.put(req);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值