// 普通使用线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class TestThread {
/**
* @param args
*/
public static void main(String[] args) {
try {
ExecutorService es = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) { // 由于线程池 大小为2,所以总的只会启动2个线程。
es.execute(new Print());
}
es.shutdown();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class Print implements Runnable {
@Override
public void run() {
while(true) {
System.out.println("..running" + Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// --------------- 网络应用线程池 --- 转载
public class NetworkService {
private final ServerSocket serverSocket;
private final ExecutorService pool;
public NetworkService(int port, int poolSize) throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);
}
public void run() { // run the service
try {
for (;;) {
pool.execute(new Handler(serverSocket.accept()));
}
} catch (IOException ex) {
pool.shutdown();
}
}
}
class Handler implements Runnable {
private final Socket socket;
Handler(Socket socket) {
this.socket = socket;
}
public void run() {
// read and service request on socket
}
}