按位運算子在java中的應用?

runc發表於2013-04-22
如nio中selectionKey類

public static final int OP_CONNECT = 1 << 3;

    /**
     * Operation-set bit for socket-accept operations.  </p>
     *
     * <p> Suppose that a selection key's interest set contains
     * <tt>OP_ACCEPT</tt> at the start of a <a
     * href="Selector.htmlselop">selection operation</a>.  If the selector
     * detects that the corresponding server-socket channel is ready to accept
     * another connection, or has an error pending, then it will add
     * <tt>OP_ACCEPT</tt> to the key's ready set and add the key to its
     * selected-key&nbsp;set.  </p>
     */
    public static final int OP_ACCEPT = 1 << 4;
<p class="indent">



還有這樣使用

 final SelectionKey key = it.next();
                            final SelectorListener listener = (SelectorListener) key.attachment();
                            logger.debug("key : {}", key);
                            int ops = key.readyOps();
                            boolean isAcceptable = (ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT;
                            boolean isConnectable = (ops & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT;
                            boolean isReadable = (ops & SelectionKey.OP_READ) == SelectionKey.OP_READ;
                            boolean isWritable = (ops & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE;
                            listener.ready(isAcceptable, isConnectable, isReadable, isReadable ? readBuffer : null,
                                    isWritable);
                            // if you don't remove the event of the set, the selector will present you this event again and
                            // again
                            logger.debug("remove");
                            it.remove();
<p class="indent">


這樣使用有什麼好處呢?為什麼要這樣寫呢?

相關文章