非阻塞同步

非阻塞同步:
client:
public class SocketClientDaemon {
    public static void main(String[] args )throws Exception{
        CountDownLatch countDownLatch = new CountDownLatch(10);
        //开启10个线程 ,同时发送
        for(int i=0; i<10;i++,countDownLatch.countDown()) {
            SocketClientRequestThread socketClientRequestThread = new SocketClientRequestThread(countDownLatch, i);

  
  
public class SocketClientDaemon {
    public static void main(String[] args )throws Exception{
        CountDownLatch countDownLatch = new CountDownLatch(10);
        //开启10个线程 ,同时发送
        for(int i=0; i<10;i++,countDownLatch.countDown()) {
            SocketClientRequestThread socketClientRequestThread = new SocketClientRequestThread(countDownLatch, i);
            new Thread(socketClientRequestThread).start();
        }
        //这个wait不涉及到具体的实验逻辑,只是为了保证守护线程在启动所有线程后,进入等待状态
        synchronized (SocketClientDaemon.class) {
            SocketClientDaemon.class.wait();
        }
    }
}
用户请求发送消息:
public class SocketClientRequestThread implements  Runnable {
    static  {
        BasicConfigurator.configure();
    }
    private static final Log Logger = LogFactory.getLog(SocketClientRequestThread.class);
    private CountDownLatch countDownLatch;
    private Integer clientIndex; //线程编号
    public SocketClientRequestThread(CountDownLatch count,Integer cliendCount){
        this.clientIndex = cliendCount;
        this.countDownLatch = count;
    }
    @Override
    public void run(){
        Socket  socket = null ;
        OutputStream clientRequest = null;
        InputStream clientResponse = null;
        try{
            socket = new Socket("localhost",83);
            clientRequest = socket.getOutputStream();
            clientResponse = socket.getInputStream();
            //等待,直到所有的线程已经全部启动
            countDownLatch.await();
            clientRequest.write(("发送消息了--"+clientIndex+"  .over").getBytes());
            clientRequest.flush();
            System.out.println("-----------------");
            //在这里等待,直到服务器返回信息
            System.out.println("第" + this.clientIndex + "个客户端的请求发送完成,等待服务器返回信息");
            int maxLen = 1024;
            byte[] contextBytes = new byte[maxLen];
            int realLen;
            String message = "";
            //程序执行到这里,会一直等待服务器返回信息(注意,前提是in和out都不能close,如果close了就收不到服务器的反馈了)
            while((realLen = clientResponse.read(contextBytes, 0, maxLen)) != -1) {
                message += new String(contextBytes , 0 , realLen);
            }
            System.out.println("接收到来自服务器的信息:" + message);


        }catch (Exception e){

        }
        finally {
            try {
                clientRequest.close();
                clientResponse.close();
                socket.close();
            }catch (IOException o)
            {
                o.printStackTrace();
            }
        }
    }
}

   
   
服务端:
public class SocketServer3 {

    static {
        BasicConfigurator.configure();
    }
    private static Object xWait = new Object();
    /**
     * 日志
     */
    private static final Log LOGGER = LogFactory.getLog(SocketServer3.class);

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(83);
            serverSocket.setSoTimeout(2000);
            while(true) {
                Socket socket = null;
                try {
                    socket = serverSocket.accept();
                } catch(SocketTimeoutException e1) {
                    //===========================================================
                    //      执行到这里,说明本次accept没有接收到任何TCP连接
                    //      主线程在这里就可以做一些事情,记为X
                    //===========================================================
                    synchronized (SocketServer3.xWait) {
                        SocketServer3.LOGGER.info("这次没有从底层接收到任何TCP连接,等待2100毫秒,模拟事件X的处理时间");
                        SocketServer3.xWait.wait(100);
                    }
                    continue;
                }
                //开线程去读数据
                new Thread(new SocketServerThread(socket)).start();
            }
        } catch(Exception e) {
            SocketServer3.LOGGER.error(e.getMessage(), e);
        } finally {
            if(serverSocket != null) {
                serverSocket.close();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值