Java Threading

Suppose you have to handle two kinds of request from client in different priority and scheduling, here comes the threading design.

class EthProvService {

RequestHandlerThread rt = new RequestHandlerThread();

rt.start(); // start thread

PollingThread pt = new PollingThread();

while (true) {

pt.start();

sleep(seconds);

}

};

class RequestHandlerThread extends thread {

public RequestHandlerThread(){};

public void run() { // do something

if (request is of type A) doA;

....

};

}

class PollingThread extends thread {

public PollingThread() {};

public void run() { // do something

if (polling record is of type A) doA;

...

}

}

If the polling thread is low priority and always run on behalf of RequestHandlerThread, then it can be done as a daemon thread.

A daemon thread is run in the background. To create a daemon thread, invoke thread.setDaemon(true);

Another important design in multi-threading is how to access common resource data.

wait(), notify(), notifyAll(); are methods to use to inter-communicate within threading objects.

synchronized keyword must be added to protect the block of code from multiple update/read concurrently.

read more examples on how to handle multi-threading concurrency in http://www.datadisk.co.uk/html_docs/java/threads.htm