import java.util.Random; /** * 指数退避算法: */ public class ExponentialBackoffAlgorithm { static final int netSpeed = 10*1000;// 网速(b/ms) static final double dataLength = 200;// 数据长度(字节) static final int maxTime = 16;// 最大重传的次数 static final double contentionPeriod = dataLength*8/netSpeed; public static void main(String[] args) { System.out.println("最大重传的次数为:"+maxTime); System.out.println("争用期时间为:"+contentionPeriod); System.out.println(); int k = 0; // 重传的次数 while (true) { if(!send()) //如果发生碰撞 { k++; if (k <= maxTime) // 最大重传送次数为maxTime { System.out.println("***发生碰撞!" + "准备进行第" + k + "次重传!***"); backoff(k); }else{ System.out.println("重传maxTime次仍未成功,丢弃!"); break; } }else { System.out.println("本次未发生碰撞,传送成功!!共重传" + k + "次。"); break; } } } private static int getRand(int max) // 得到min到max之间的一个随机数 { int r ; Random random = new Random(); r=random.nextInt(max+1); return r ; } private static int twoPowerK(int k) // 二的k次幂 { int a = 2; int f = 1; for(int i = k ; i>0 ;i --) { f *= a; } return f; } static void backoff(int i) { int r, max; double backTime; System.out.println("开始退避操作!"); max = twoPowerK(i) - 1; System.out.println("随机数范围:"+"0到"+max); r=getRand(max); System.out.println("得到的随机数r为:"+r); backTime = r * contentionPeriod; System.out.println("退避时间为:"+contentionPeriod+"*"+r+"="+backTime+"豪秒"); try { Thread.sleep((long)(backTime)); //退避 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("退避完成!"); } static boolean send() { //发送逻辑 System.out.println("发送失败!"); System.out.println(" "); return false; } }