package com.mode;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
public class suspension {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i <3 ; i++) {
reciver t =new reciver();
t.setName(""+i);
t.start();
}
Thread.sleep(1000);
for(int id:emailbox.getids()){
Postman postman= new Postman(id,"内容:"+id);
postman.setName(""+id);
postman.start();
}
}
}
class reciver extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"创建邮箱");
protect pt=emailbox.Createprotect();
System.out.println(Thread.currentThread().getName()+"开始收信");
Object message=pt.getResults(2000);
System.out.println(Thread.currentThread().getName()+"收到信:id="+pt.getId()+"\t 内容:"+message);
}
}
class Postman extends Thread{
private int id;
private String mail;
public Postman(int id, String mail) {
this.id = id;
this.mail = mail;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始送信..");
protect pt=emailbox.get(id);
System.out.println("送信id:"+id+"\t "+mail);
pt.stop(mail);
}
}
class emailbox{
private static int id=0;
private static Map<Integer,protect> map=new Hashtable<>();
public static synchronized int generater(){
id++;
return id;
}
public static protect get(int id){
return map.remove(id);
}
public static synchronized protect Createprotect(){
protect p=new protect(generater());
map.put(p.getId(),p);
return p;
}
public static Set<Integer> getids(){
return map.keySet();
}
}
class protect{
private int id=0;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public protect(int id) {
this.id = id;
}
private Object result;
public Object getResults(long timeout){
synchronized (this){
long now=System.currentTimeMillis();
long pass=0;
while (result==null){
long waittime=timeout-pass;
if(waittime<=0) break;
try {
wait(waittime);
} catch (InterruptedException e) {
e.printStackTrace();
}
pass=System.currentTimeMillis()-now;
}
return result;
}
}
public void stop(String message){
synchronized (this){
result=message;
notifyAll();
}
}
}