What is a correct way to run multiple threads that do different jobs in java?
I am trying to build a network related program in Java. I have previous experience with C. In C, when you run thread, you define which method you want it to be run as a thread.
However, in Java, it seems that thread always runs with method run()
and there can be 1 method with that name in each class.
I want to have at least 2 threads, one thread for working on calculations, and one thread to work on communications with other applications. (Even if this can be done with 1 thread, I just want to know what would be a correct way to run 2 threads that does totally different jobs)
Below is just a sample code how I implemented the thread. If thread generated by below codes does communication, what would be a nice way to create another thread that does calculation?
public class Server implements Runnable{
static Thread myThread;
public void run() {
// TODO Auto-generated method stub
}
public static void main(Strin开发者_如何转开发g[] args) {
myThread = new Thread(new Server());
}
}
Don't put a main
method in the class that implements Thread
or Runnable
. You could implement what you want with your current Server
implementation, but I don't see a good reason to do so. Separate out the concerns, and KISS:
- One boring, simple class with a
public static void main(String[] args)
method - One
Server implements Runnable
class (one type of thread) - One
Calculations implements Runnable
class (the other type of thread)
The class with the main
method would start the Server
and Calculations
threads.
Use Executors.newSingleThreadExecutor()
to create a thread pool containing a single thread. Submit Callable
objects to this Executor
, where each instance will perform one of your calculations. A Future
object is returned that can be used to fetch the result of the calculation. The calculation itself will be running in a thread managed by the Executor.
精彩评论