Jay
Jay

Reputation: 568

How can I implement threads in this scenario?

I haven't got any code at the moment but I have a situation where I will be implementing an Java application onto a wireless sensor. There can only be one main method.

There will be multiple other wireless sensors that can connect to my sensor. My sensor needs to do a calculation based on thhe information provided to me by the other sensors. Each sensor can choose whether or not they want to participate in the calculation. Every 1 second, my sensor does a calculation.

So basically, what I need is to listen for incoming sensors, provide them with a thread to interact with, and retrieve the information from each sensor.

My question is, in my application, how do I listen for incoming sensors (blocking call) and also free my application to carry out its calculations?

Upvotes: 1

Views: 121

Answers (3)

Java42
Java42

Reputation: 7716

This will get you started. Add error/exception checking/handling as necessary.

public class Test { 
  static class WorkTask42 implements Runnable { 
    public void run() { 
       // background work            
    } 
  } 
  public static void main(String... args) throws Exception { 
    // repeat for each background task
    WorkTask42 wt = new WorkTask42();  
    Thread a = new Thread(wt);  
    a.setDeamon(true);
    a.start(); 
  } 
} 

Upvotes: 0

toto2
toto2

Reputation: 5326

You need another thread that receives the information of all the communication threads. You should look at the utilities in java.util.concurrent such a BlockingQueue that let threads pass data to one another thread-safely.

Most of all you should read a lot about multi-threading: it is not a trivial topic.

Upvotes: 1

Chris Thompson
Chris Thompson

Reputation: 35598

From a high level, this is what your application will do

==Main Thread==

  1. start socket
  2. Start processing thread
  3. accept an incoming connection (this will cause the thread to block until a connection occurs)
  4. start new thread to handle socket (handler thread) (alternatively use a thread pool, but that is more complicated)
  5. return to 3

==Handler Thread==

  1. Receive open socket from main thread
  2. Save data coming in from socket to be given to processing thread
  3. Finish and close socket

==Processing Thread==

  1. Wait 1 second
  2. Process data retrieved from step 2 of Handler Thread
  3. Return to 1

Upvotes: 1

Related Questions