问题
I got a Socket Server running as a Java SwingWorker.
The SwingWorker receives incoming connections, and upon connection, hands over the socket to an Executor that takes care of the connection. The Executor calls a SocketHandler that will handle the socket via the run() method.
Now, I have one button on the GUI that says stop. I want to stop the SwingWorker from execution when i press the Stop button. To do so, I had a cancel(true) method called upon pressing the Stop button.
Now, the SocketHandler continues receiving incoming data despite my program calling the cancel(true) method. What's going on here?
I had read thru couple articles that it's a bug within the JDK that calling cancel(true) method does not stop the SwingWorker. Is this true?
回答1:
simply add a boolean checker in the loop
if (!stillWorking)return;
then you can set the boolean to false to stop the method.
回答2:
API for public final boolean cancel(boolean mayInterruptIfRunning)
:
"mayInterruptIfRunning
- true
if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete".
You have to read on Thread.interrupt
. It actually does not interrupt anything; you have to specify in your code how to deal with interrupts.
Also, it's not clear from your question if you just want to stop the main SwingWorker
from taking connections or if you want to kill all existing connections too.
EDIT: If you do have a while
loop in the thread accepting the connections:
while (!Thread.interrupted()) {
should be sufficient, I guess.
Now when the SwingWorker
is cancelled, the loop should stop because the SwingWorker
thread has it inner interrupt flag set.
回答3:
@Yakult121 please this isn't answer to your both questions Java SwingWorker Socket Server does not get cancelled when i cancel the the SwingWorker and Java SwingWorker - using publish/process to update a TextArea in EDT? , I think that your question not fully described, I miss there lots of importan details,
you have to post code for better ..., that demostrated your implementations for Executor, SwingWorker and cancelation for that
your code could be based on this two threads, too
1/ Cancel SwingWorker
2/ Executor And SwingWorker
3/ and how/what you determine concrete SwingWorker's thread for cancelations
4/ really put your two thread together
来源:https://stackoverflow.com/questions/6283541/java-swingworker-socket-server-does-not-get-cancelled-when-i-cancel-the-the-swin