文章目录
Java多线程相关知识【15】--设计模式--确保挂起模式(Guarded Suspension)1.问题的引入2.问题的解决3.实现的代码请求队列请求体连接端服务端使用方法
菜鸟的一个学习笔记,欢迎大神
批评指正。
Java多线程相关知识【15】–设计模式–确保挂起模式(Guarded Suspension)
1.问题的引入
一个线程正在做一个非常关键的任务,这时,有一个其他的线程让当前线程做其他的事情,当前线程只有完成当前的任务才能做其他的任务。
2.问题的解决
使用队列将其他需要工作的线程保存,然后在未来需要时,继续取队列中获取任务,然后执行。
3.实现的代码
请求队列
package com
.company
.ThreadCharPart2
.guardedsuspension
;
import java
.util
.LinkedList
;
public class GuardedSuspensionQueue {
LinkedList
<GuardedSuspension> queue
= new LinkedList<>();
public GuardedSuspension
getGuardedSuspension() {
synchronized (queue
) {
while (queue
.size() <= 0) {
try {
queue
.wait();
} catch (InterruptedException e
) {
return null
;
}
}
return queue
.removeFirst();
}
}
public void putGuardedSuspension(GuardedSuspension guardedSuspension
) {
synchronized (queue
) {
queue
.addLast(guardedSuspension
);
queue
.notifyAll();
}
}
}
请求体
public class GuardedSuspension<T> {
final private T value
;
public GuardedSuspension(T value
) {
this.value
= value
;
}
public T
getValue() {
return value
;
}
}
连接端
public class GuardedSuspensionClientThread<T> extends Thread {
private final GuardedSuspensionQueue queue
;
private final T value
;
private final Random random
;
public GuardedSuspensionClientThread(GuardedSuspensionQueue queue
, T value
) {
this.queue
= queue
;
this.value
= value
;
this.random
= new Random(System
.currentTimeMillis());
}
@Override
public void run() {
for (int i
= 0; i
< 10; i
++) {
System
.out
.println("This client value ->"+value
);
queue
.putGuardedSuspension(new GuardedSuspension(value
));
try {
Thread
.sleep(random
.nextInt(1000));
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
}
}
服务端
public class GuardedSuspensionServerThread extends Thread {
private final GuardedSuspensionQueue queue
;
private final Random random
;
private volatile boolean close
= false;
public GuardedSuspensionServerThread(GuardedSuspensionQueue queue
) {
this.queue
= queue
;
random
= new Random(System
.currentTimeMillis());
}
@Override
public void run() {
while (!close
) {
GuardedSuspension suspension
= queue
.getGuardedSuspension();
if (suspension
== null
) {
System
.out
.println("error");
continue;
}
System
.out
.println("Server ->" + suspension
.getValue());
try {
Thread
.sleep(random
.nextInt(1000));
} catch (InterruptedException e
) {
return;
}
}
}
public void close() {
this.close
= true;
this.interrupt();
}
}
使用方法
public class GuardedSuspensionClient {
public static void main(String
[] args
) throws InterruptedException
{
final GuardedSuspensionQueue queue
= new GuardedSuspensionQueue();
new GuardedSuspensionClientThread(queue
, "test").start();
GuardedSuspensionServerThread guardedSuspensionServerThread
= new GuardedSuspensionServerThread(queue
);
guardedSuspensionServerThread
.start();
Thread
.sleep(11000L
);
guardedSuspensionServerThread
.close();
}
}