Asked  6 Months ago    Answers:  5   Viewed   18 times

Could you explain what java.lang.Thread.interrupt() does when invoked?

 Answers

78

Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.

Polling occurs via the Thread.interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.

EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.

  • Object.wait(), Thread.sleep(), and Thread.join()
  • Most java.util.concurrent structures
  • Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.

EDIT (from @thomas-pornin's answer to exactly same question for completeness)

Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop() that is more like shooting the thread with an assault rifle.

Tuesday, June 1, 2021
 
waylaidwanderer
answered 6 Months ago
87

Addslashes is generally not good enough when dealing with multibyte encoded strings.

Wednesday, March 31, 2021
 
AntoineB
answered 9 Months ago
89

Task implements Runnable, so when you call handler.run(); you actually run the call method in the UI Thread. That will hang the UI.

You should start the task in a background thread, either via an executor or simply by calling new Thread(handler).start();.

This is explained (maybe not very clearly) in the javadoc or in the JavaFX concurrency tutorial.

Wednesday, July 28, 2021
 
kwichz
answered 4 Months ago
36

The basic rules for threading in JavaFX (and forgive me if you already understand some of this, I just want to be complete) are:

  1. Anything that blocks execution (or takes a long time to execute) should be run on a background thread - not on the FX Application Thread
  2. Anything that changes the state of a Node that is part of the scene graph should be executed on the FX Application Thread

In order to help achieve these, the JavaFX API provides a Task class. This has a call() method that returns a value; it is a Runnable so can be provided as the argument to a Thread constructor, or passed to an Executor. It also provides useful callbacks that are guaranteed to be executed on the FX Application Thread, such as setOnSucceeded, setOnFailed, and various update...() methods that update properties such as progress and message on the FX Application Thread.

However, the Task class is really designed for one-off tasks: think about applications that need to retrieve data from a database, for example, which may take time. These execute a specific action and return a result. Your case is somewhat different, in that your thread is executing continuously.

In this case, it's probably better to use a simple Thread and use Platform.runLater(...) to update the UI. Platform.runLater(...) takes a Runnable and executes its run() method on the FX Application Thread.

It's not clear to me why your code is behaving the way you describe, but assuming the method call snake.updatePosition() causes a change in the UI, that should be executed on the FX Application Thread. In any case I would try

taskThread = new Thread(new Runnable() { 
    public void run() {
            while(!Thread.currentThread().isInterrupted()){
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        snake.updatePosition();
                    }
                });
                try{
                    Thread.sleep(1000);
                } catch(InterruptedException e){
                    break;
                }
            }
    }
});

If you are using Java 8, this all looks a lot nicer with lambdas replacing the anonymous inner classes:

taskThread = new Thread( () -> {
    while (! Thread.currentThread().isInterrupted()) {
        Platform.runLater( snake::updatePosition );
        try {
            Thread.sleep(1000);
        } catch (InterruptedException exc) {
            break ;
        }
    }
});

One other technique in JavaFX for executing something periodically is to (ab?)use an Animation:

    Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), 
        new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                snake.updatePosition();
            }
        }
    ));
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();

or, in Java 8, the somewhat slick

    Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), 
        event -> snake.updatePosition()));
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();
Saturday, August 7, 2021
 
Gabriele
answered 4 Months ago
28

It is a do-while loop. So it will do everything in the following block while count is less than or equal to 5. The difference between this and a normal while loop is that the condition is evaluated at the end of the loop not the start. So the loop is guarenteed to execute at least once.

Sun tutorial on while and do-while.

Oh, and in this case it will print:

1, 2
1, 2, 3, 4

Edit: just so you know there will also be a new line at the start, but the formatting doesn't seem to let me show that.

Monday, August 23, 2021
 
Asperi
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share