I am implementing simple version of TCP, but lack of multi-thread technique. The main thread controls 2 sub threads:
1. timer(counting down time, if timeout, inform main thread to do some job again)
2. listening incoming packet, loop forever. if packet is received, then update some data in main thread
The main thread should take action when a certain signal occurs.
I have no experience with event handling and design some signal to inform main thread.
Where should I start? For example, the sub thread updates main thread private field. Or should I create some event?
Here’s some pseudo code for the main thread:
while(true){
event: send data ,then ...
event: timeout , then send packet again
event: packet received, then update data in private filed
}
If you are new to the concept of multithreading in Java, I suggest reading this tutorial first: http://docs.oracle.com/javase/tutorial/essential/concurrency/
Discussing your specific issue, you should have two threads:
– one for listening to your socket, which will extend thread. It should receive a reference to your main object at construction time and keep listening to your socket. When something arrives, this thread will call the treatment routine for the main object to take action. Be careful only with busy waiting – yield for some time while socket is not ready.
– your timer could be an extension of TimerTask. have a look at http://www.cloudhadoop.com/2012/01/timers-in-java-create-timer-in-java.html in order to understand more.