Java 服務器示例
在本文剩余部分
清單
import ncurrent
import ncurrent
import ncurrent
class Server {
private ExecutorService threadPool;
Server(int numThreads) {
ThreadFactory theFactory = new ThreadFactory();
this
}
public void start() {
while (true) {
// main server handling loop
// create a
TaskHandler task = new TaskHandler();
this
}
this
}
public static void main(String[] args) {
int serverThreads = Integer
Server theServer = new Server(serverThreads);
theServer
}
}
class TaskHandler extends Runnable {
public void run() {
// code to handle a
}
}
此服務器可以創建所有需要的線程
清單
import java
class TaskHandler implements Runnable {
static public int N=
static public int M=
static long result=
// constant work per transaction
public void run() {
long dispatchTime = System
long x=
for (int j=
for (int i=
x = x + i;
}
}
result = x;
long endTime = System
Server
}
}
此 run() 方法中的循環計算 N (
我們使此應用程序稍微真實一些
清單
class GCStressThread extends Thread {
HashMap<Integer
volatile boolean stop = false;
class BinaryTree {
public BinaryTree left;
public BinaryTree right;
public Long value;
}
private void allocateSomeData(boolean useSleep) {
try {
for (int i=
if (useSleep)
Thread
BinaryTree newTree = createNewTree(
this
}
} catch (InterruptedException e) {
stop = true;
}
}
public void initialize() {
this
allocateSomeData(false);
System
}
public void run() {
while (!stop) {
allocateSomeData(true);
}
}
}
GCStressThread 通過 HashMap 維護一組 BinaryTree
我們不打算使用客戶端來驅動此服務器
清單
public void start() {
for (int m=
TaskHandler task = new TaskHandler();
threadPool
}
try {
while (!serverShutdown) { // boolean set to true when done
Thread
}
}
catch (InterruptedException e) {
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25863.html