[java] threads stoppen

Pagina: 1
Acties:

  • Zynth
  • Registratie: September 2001
  • Laatst online: 20-05 19:47
Ik ben bezig met een programma met threads. Nu is mijn vraag: Hoe stop ik een thread? De methode stop is uit de libraries gehaald, destroy geeft errors en interrupt stopt de thread helemaal niet.

zelfs als ik de exception van dit destroyen catch, krijg ik nog de error...

  • Scorpion
  • Registratie: April 2000
  • Laatst online: 18-01-2024

Scorpion

not to lame to read BitchX.doc

Je moet zelf iets inbouwen, omdat de stop() deprecated is (dit was geen slimme oplossing omdat er data verloren kon gaan door het abrupt stoppen van een thread).

Je kunt het volgende dus doen als vervanging van de deprecated Thread.stop():
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class myThread extends Thread {

  private boolean stop = false;

  public void run() {
    while(!stop) {
    // doe iets
    try {
      sleep(1000);
    } catch(InterruptedException ie) {
    }
    }
  }

  public void stoppen() {
    stop = true;
  }

}

have fun :)

  • marcusk
  • Registratie: Februari 2001
  • Laatst online: 26-09-2023
Of meer standaard: while (! isInterrupted()). Dan kun je de interrupt() methode gebruiken.

  • Stephan Oudmaijer
  • Registratie: Oktober 2000
  • Laatst online: 16-08-2023
What should I use instead of Thread.stop?

Most uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. (This is the approach that JavaSoft's Tutorial has always recommended.) To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized).

For example, suppose your applet contains the following start, stop and run methods:

private Thread blinker;

public void start() {
blinker = new Thread(this);
blinker.start();
}

public void stop() {
blinker.stop(); // UNSAFE!
}

public void run() {
Thread thisThread = Thread.currentThread();
while (true) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}


You can avoid the use of Thread.stop by replacing the applet's stop and run methods with:

private volatile Thread blinker;

public void stop() {
blinker = null;
}

public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
thisThread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}




How do I stop a thread that waits for long periods (e.g., for input)?

That's what the Thread.interrupt method is for. The same "state based" signaling mechanism shown above can be used, but the state change (blinker = null, in the previous example) can be followed by a call to Thread.interrupt, to interrupt the wait:

public void stop() {
Thread moribund = waiter;
waiter = null;
moribund.interrupt();
}


For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:

Thread.currentThread().interrupt();


This ensures that the Thread will reraise the InterruptedException as soon as it is able.



What if a thread doesn't respond to Thread.interrupt?

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.

  • Zynth
  • Registratie: September 2001
  • Laatst online: 20-05 19:47
eh ;)
Ik was bezig met threads en sockets in java en kwam er niet uit.
Vandaar dat ik op tweakers zocht en notabene een vraag van mijzelf
van vroeger tegenkwam :)
Alleen voor mijn huidige toepassing kom ik er niet helemaal uit.
Ik heb een Thread voor elke naar mij geconnecte client (ik ben de server).
Alleen, als ik iemand wil 'kicken' dan meld ik hem netjes overal af in mijn software
maar op het laatst moet ook zijn thread verwijderd worden.
Het probleem is dat die thread bijna de gehele tijd staat te wachten met een
in.readLine(); (voor de socket).

Nou vroeg ik me af; wanneer wordt een thread eigenlijk verwijderd?
Gebeurd dit als de run-methode klaar is en dus wordt afgesloten?
Ik had namelijk het idee;
als ik iemand wil kicken terwijl de socket staat te luisteren naar hem,
(in.readLine()) dan roep ik in.close() aan, stopt de blocking readline en
sluit de thread af. klopt dit?
of moet dit met een interrupt :|

  • Soultaker
  • Registratie: September 2000
  • Laatst online: 23-05 18:13
Als je de thread wilt onderbreken is het sowieso handig om te beginnen door de interrupt methode aan te roepen. Je threadcode moet dan zelf de status in de gate houden (met Thread.isInterrupted() en afsluiten op een geschikt punt.

Over de interrupt methode zegt de API documentatie het volgende:
[..]

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

[..]
If none of the previous conditions hold then this thread's interrupt status will be set.
De readline methode is sowieso een I/O operation. Of die interruptable is weet ik niet. Zo ja, dan is er geen probleem en zou de thread via de normale afhandeling van de exception onderbroken kunnen worden. Zo nee, dan kun je proberen om de operaties te onderbreken door de socket te sluiten zoals je al aangeeft. Met TCP (en in Java misschien zelfs alle) sockets zou dat wel moeten werken. In dit geval kan het dus een oplossing zijn, maar in het algemene geval kun je niet elke mogelijke operatie op deze manier onderbreken.
Pagina: 1