-
guarded是“被保护着的”、“被防卫着的”意思。当现在并不适合马上执行某个操作时,就要求想要执行该操作的线程等待,以保障实例的安全性。(暂停的是服务器的端的线程)。
-
Request
public class Request {
final private String value;
public Request(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
- RequestQueue
public class RequestQueue {
private Queue<Request> queue = new LinkedList<>();
public synchronized void putRequest(Request request){
queue.offer(request);
notifyAll();
}
public synchronized Request getRequest(){
while (queue.peek() == null){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return queue.remove();
}
}
- ClientThread
public class ClientThread extends Thread {
private final RequestQueue queue;
private final Random random;
private final String sendValue;
public ClientThread(RequestQueue queue, String sendValue) {
this.queue = queue;
this.sendValue = sendValue;
random = new Random(System.currentTimeMillis());
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Client -> request " + sendValue);
queue.putRequest(new Request(sendValue));
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- ServerThread
public class ServerThread extends Thread {
private final RequestQueue queue;
private final Random random;
private volatile boolean closed = false;
public ServerThread(RequestQueue queue) {
this.queue = queue;
random = new Random(System.currentTimeMillis());
}
/**
* server三种被中断的方式:
* 1:正要运行的时候发现closed标识已经为true了
* 2:处于wait状态。closed起不到作用,调用close方法中断,request返回null
* 3: sleep的时候被中断
*/
@Override
public void run() {
while (!closed) {
Request request = queue.getRequest();
if (null == request) {
System.out.println("Received the empty request.");
continue;
}
System.out.println("Server ->" + request.getValue());
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
return;
}
}
}
public void close() {
this.closed = true;
this.interrupt();
}
}
- 调用类
public class SuspensionClient {
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();
//serverThread.join();
Thread.sleep(10000);
serverThread.close();
}
}
网友评论