Creating Threads (Lea (2nd ed.)
for (;;)
{
accept request
create task
}
class WebService implements Runnable
{
static final int PORT = 1040;
Handler handler = new Handler();
public void run() {
try {
ServerSocket socket =
new ServerSocket(PORT);
for (;;) {
final Socket connection = socket.accept();
new Thread ( new Runnable() {
public void run() {
handler.process(connection);
}}).start();
}
}
catch(Exception e) {} //die
}
public static void main(String[] args) {
new Thread(new WebService()).start();
}
}
class Handler {
void process(Socket s) {
DataInputStream in = null;
DataOutputStream out = null'
try {
in = new DataInputStream(s.getInputStream());
out = new DataOutputStream(s.getOutputStream());
int request = in.readInt(); //return negation to client
int result = -request;
out.writeInt(result);
}
catch(IOException ex) {}
//fall through
finally
{
//clean up
try{if(in != null) in.close();
}
catch (IOException
ignore) {}
try {if(out != null) out.close();
}
catch (IOException
ignore) {}
try {s.close(); }
catch (IOException
ignore) {}
}
}
}
class PlainWorkerPool implements
Executor {
protected final Channel workQueue;
public void execute(Runnable r) {
try {
workQueue.put(r);
}
catch (InterruptedException ie) { //postpone response
Thread.currentThread();.interrupt();
}
}
public PlainWorkerPool(Channel
ch, int nworkers)
{
workQueue = ch;
for (int i= 0; i< nworkers; ++i) activate();
}
protected void activate() {
Runnable runLoop = new Runnable()
{
public void run() {
try {
for (;;) {
Runnable r =
(Runnable)(workQueue.take());
r.run();
}
}
catch (InterruptedException
ie) {} //die
}
};
new Thread(runLoop).start();
}
}