Reputation: 469
I have a couple questions about he following code:
final Runnable accept = new Runnable() {
public void run() {
while (connect == true) {
try {
sock = servsock.accept();
}
catch (Exception e) {
System.out.println(e);
}
}
}
};
new Thread(accept).start(); //creates new instance every time i want to run accept()
See, every time I want to run 'accept', I create a new thread instance and start it. Can someone tell me how to stop one of these threads? Like, how do I identify the thread? Should I rather use an array of threads?
Upvotes: 2
Views: 62
Reputation: 1856
Are you using JDK 7? How about this approach?
ExecutorService tPool = Executors.newFixedThreadPool(5);
InterruptableTask task = new InterruptableTask();
Map<Integer, InterruptableTask> tasks = new HashMap<Integer, InterruptableTask>();
tasks.put(0, task);
Future future = tPool.submit(task);
// something is executed here...
InterruptableTask it = tasks.get(0);
it.suspend();
Upvotes: 1
Reputation: 334
If you're trying to maintain a thread pool look at java.util.concurrent.ExecutorService and java.util.concurrent.Executors there web is well stocked with examples of their use.
Upvotes: 0
Reputation: 35096
The best way to accept sockets on a ServerSocket is to run the accept loop in 1 thread, and then pass off the newly spawned/accepted socket to another thread.
How to stop your threads? Easiest, best way is to close the Sockets that they are listening on.
Upvotes: 1