按位运算符在java中的应用?

13-04-22 runc
如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.html#selop">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>

还有这样使用

 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>

这样使用有什么好处呢?为什么要这样写呢?

banq
2013-04-22 16:51
快,处理器能够直接支持:

http://en.wikipedia.org/wiki/Bitwise_operation

猜你喜欢