banq,怎么不回我帖呢?给别人回,都不给我回,你是不是只挑你能回答的,答不了的就装没看见!

06-02-09 xh
上次发的文章,点这里,就是第一章的第一个代码的run的执行过程!

public class TCPReactor implements Runnable {

private final static String module = TCPReactor.class.getName();

private final Selector selector;

private final ServerSocketChannel ssc;

public TCPReactor(int port) throws IOException {

selector = Selector.open();

ssc = ServerSocketChannel.open();

InetSocketAddress address =

new InetSocketAddress(InetAddress.getLocalHost(), port);

ssc.socket().bind(address);

Debug.logVerbose("-->Start host:" + InetAddress.getLocalHost() + " port=" +

port);

ssc.configureBlocking(false);

//向selector注册该channel

SelectionKey sk = ssc.register(selector, SelectionKey.OP_ACCEPT);

//利用sk的attache功能绑定Acceptor 如果有事情,触发Acceptor

sk.attach(new Acceptor(selector, ssc));

Debug.logVerbose("-->TCP Server started");

}

public void run() {

while (true) {

try {

selector.select();

Set selected = selector.selectedKeys();

Iterator it = selected.iterator();

//Selector如果发现channel有OP_ACCEPT或READ事件发生,下列遍历就会进行。

while (it.hasNext())

//来一个事件 第一次触发一个accepter线程

//以后触发SocketReadHandler

dispatch( (SelectionKey) (it.next()));

selected.clear();

} catch (IOException ex) {

Debug.logError("reactor error" + ex, module);

}

}

}

//运行Acceptor或SocketReadHandler

private void dispatch(SelectionKey key) {

Runnable r = (Runnable) (key.attachment());

if (r != null) {

r.run();

}

}

}

public class Acceptor implements Runnable {

private final Selector selector;

private final ServerSocketChannel ssc;

public Acceptor(Selector selector, ServerSocketChannel ssc) {

this.selector = selector;

this.ssc = ssc;

}

public void run() {

try {

SocketChannel sc = ssc.accept();

if (sc != null) {

sc.configureBlocking(false);

SelectionKey sk = sc.register(selector, 0);

//同时将SelectionKey标记为可读,以便读取。

sk.interestOps(SelectionKey.OP_READ);

selector.wakeup();

sk.attach(new TCPHandler(sk, sc));

}

} catch (Exception ex) {

Debug.logVerbose("accept stop!" + ex);

}

}

}

这里的dispatch的run是执行谁的run,是Acceptor的还是TCPReactor的.

我又想了遍,好象是Acceptor(由于attach作用)的,是不是?

banq你又不回我帖嘛

banq
2006-02-09 19:05
线程我很长时间没有碰了,所以不是很记得,本站有专门这方面文章,你可仔细研究。

http://www.jdon.com/concurrent.htm

xh
2006-02-09 23:08
就只问你一点dispatch的run是运行Acceptor还是TCPReactor?这个你总该知道了吧!

ishow99
2006-02-10 11:36
鄙视楼主! 你不尊重人家,谁会给你回啊!小菜就谦虚点...凸-_-凸

banq
2006-02-10 12:02
>只问你一点dispatch的run是运行Acceptor还是TCPReactor

在我上面推荐的文章中对于Dou lee的reactor原理已经解释得很清楚:

http://www.jdon.com/concurrent/reactor.htm

上面的引图很清楚吧,这是Dou Lee画的。

从图中不是可以明白看出你要的的答案吗。

猜你喜欢
2Go 1 2 下一页