并发遍历二叉树 (二)

2014-11-24 03:01:53 · 作者: · 浏览: 6
kingQueue(POOLSIZE + 2), // workQueue
new ThreadPoolExecutor.CallerRunsPolicy()); // handler
}

public void start() {
threadPool.execute(new Visitor(tree.root));
}

class Visitor implements Runnable {
private int id;
private BTreeNode node;

public Visitor(BTreeNode node) {
this.id = ++global_id;
this.node = node;
}

public boolean handleNode(BTreeNode node) {
if (node == null)
return true;

if (ConcurTravBTree.this.threadPool.getActiveCount() <= ConcurTravBTree.this.threadPool
.getCorePoolSize()) {
System.out.println("--- ActiveCount "
+ ConcurTravBTree.this.threadPool.getActiveCount());
ConcurTravBTree.this.threadPool.execute(new Visitor(node));
return true;
}
return false;
}

public void run() {
System.out.println("[ job" + id + " ] ---start ");
tasks.add(id);
if (handleNode(node.right)) // assign Node to a task
node.right = null; //

// pre-order traverse
Stack> stack = new Stack>();
while (node != null || !stack.isEmpty()) {
long start = System.currentTimeMillis();
while (node != null) {
//System.out.println("[ job" + id + " ]" + node.value);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}

stack.push(node);
node = node.left;
}
node = stack.pop();
node = node.right;

long cur = System.currentTimeMillis();
if (cur - start > 1000) {
if (handleNode(node)) {
node = null;
}
}
}
System.out.println("[ job" + id + " ] ---end");
tasks.remove(id);
if ( tasks.size() == 0) {
threadPool.shutdown();
}
}
}

public static void main(String[] args) {
ConcurTravBTree tt = new ConcurTravBTree();
System.out.println("init tree...");
tt.init();

System.out.println("start preOrderTraverse traverse...");
long start = System.currentTimeMillis();
tt.tree.preOrderTraverse();
long end = System.currentTimeMillis();
System.out.println("---- preOrderTraverse cost " + (end - start));

System.out.println("start concurrent traverse...");
long cstart = System.currentTimeMillis();
tt.start();
try {
tt.threadPool.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
long cend = System.currentTimeMillis();
System.out.println("---- current traverse cost " + (cend - cstart));
}
}

package com.pnp.javathreadpool;

import java.util.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.concurrent.Ar