Display text after releasing the Button but after a time delay - multithreading

I want to display the text after releasing the button with a delay 10 seconds. What modifications are to be done.
b1.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v)
{
t1.setText("Displaying Delay");
return false;
}
});
Thanks in advance!!

If you have access to the public static void sleep (long time) Method of the Thread class.
Causes the thread which sent this message to sleep for the given
interval of time (given in milliseconds). The precision is not
guaranteed - the Thread may sleep more or less than requested.
Parameters time The time to sleep in milliseconds.
Throws InterruptedException if the current thread has been interrupted. The
interrupted status of the current thread will be cleared before the
exception is thrown.
You try something to the extent of:
#Override
public boolean onLongClick(View v) {
try {
Thread.sleep(10000);
t1.setText("Displaying Delay");
return false;
}
catch(InterruptedException e) {}
}

Related

Execution of a thread after it got interrupted

A thread is executing task to print numbers from 0 to n, and sleeps for 4000 ms after every print statement. Somewhere in the middle thread gets interrupted. Now when the same thread starts its execution, where will it start from , will it start printing the numbers from 0 to n again, or it will print numbers from where it got interrupted.
In both cases what are the reasons and how it is being handled?
public class Main {
public static void main(String[] args) throws InterruptedException {
SleepTest sleepTest = new SleepTest();
Thread thread = new Thread(sleepTest);
thread.start();
thread.interrupt();
}
}
public class SleepTest implements Runnable{
static int sleep = 10;
public void run(){
for (int i =0; i<10; i++){
System.out.println(i);
try {
Thread.currentThread().interrupt();
Thread.sleep(4000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
System.out.println(Thread.interrupted());
}
}
Calling a interrupt() on a thread object can only suggest thread to stop. It is not guarantee that the thread will stop.
It completely depends on the implementation of run() method of thread.
In your case in run() you are catching the InterruptedException and you are printing the exception trace but not stopping the thread. Thats why thread will never stop on InterruptedException and continue the execution.
It may look like thread is getting stopped(by seeing exception trace) when see the output on console.
Refer interrupt interrupted isinterrupted in Java
All Thread.currentThread().interrupt() does is update the value of field interrupted to true.
Let's see the program's flow and how the interrupted field is assigned values:
public class Main {
public static void main(String[] args) throws InterruptedException {
SleepTest sleepTest = new SleepTest();
Thread thread = new Thread(sleepTest, "Sub Thread"); // Give a name to this thread
thread.start(); // main thread spawns the "Sub Thread". Value of "interrupted" - false
thread.interrupt(); // called by main thread. Value of "interrupted" - true
}
}
public class SleepTest implements Runnable{
static int sleep = 10;
public void run(){
System.out.println(Thread.currentThread().getName()+" "+Thread.interrupted()); // prints "Sub Thread true"
for (int i =0; i<10; i++){
System.out.println(i);
try {
Thread.currentThread().interrupt(); // no matter what value is for interrupted, it is assigned the value "true"
Thread.sleep(4000); // Can't call sleep with a "true" interrupted status. Exception is thrown. Note that, when the exception is thrown, the value of interrupted is "reset", i.e., set to false
} catch (InterruptedException exception) {
exception.printStackTrace(); // whatever
}
System.out.println(Thread.interrupted()); // returns the value of interrupted and resets it to false
}
}
To answer
where will it start from , will it start printing the numbers from 0
to n again, or it will print numbers from where it got interrupted.
Calling interrupt will not cause make it start over because all it is doing at this call is set value interrupted to false (and not modifying anything else).

Using Thread.sleep to get waiting effect in JavaFX [duplicate]

This question already has answers here:
JavaFX periodic background task
(6 answers)
Closed 5 years ago.
I want to achieve something like this: user press the login button and then label shows:
"Connecting."
0.5 sec time interval
"Connecting.."
0.5 sec time interval
"Connecting..."
etc
Just a visual effect that indicates something is actually going on "under the hood".
All I managed to get wasn't quite what I was expecting. I click the button, wait 1.5 sec and then I got "Connecting...", missing 2 previous steps.
First, my Status class
public class Status {
private static StringProperty status = new SimpleStringProperty();
public static void setStatus(String newStatus) {
status.setValue(newStatus);
}
public static String getStatus() {
return status.getValue();
}
public static StringProperty get() {
return status;
}
}
and my LoginView class
public class LoginView extends Application {
private Button loginButton = new Button("Log in");
private Label statusLabel;
private void createLabels() {
statusLabel = new Label(Status.getStatus());
statusLabel.textProperty().bind(Status.get());
}
}
private void createButtons() {
loginButton.setOnAction(e -> {
try {
Status.setStatus("Connecting.");
Thread.sleep(500);
Status.setStatus("Connecting..");
Thread.sleep(500);
Status.setStatus("Connecting...");
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
});
}
Run a Task from a different thread. Task allows you to update it's message property on the JavaFX application thread that should be used to update the GUI and must not be blocked by long-running tasks, since it's responsible for rendering:
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws InterruptedException {
updateMessage("Connecting.");
Thread.sleep(500);
updateMessage("Connecting..");
Thread.sleep(500);
updateMessage("Connecting...");
Thread.sleep(500);
return null;
}
};
// bind status to task's message
Status.get().bind(task.messageProperty());
// run task on different thread
new Thread(task).start();
You should do animations with the Timeline API. Have a look here:
https://docs.oracle.com/javase/8/javafx/api/javafx/animation/Timeline.html
Basically you just define KeyFrames at 0.5 seconds distance and set the value of the text to add a another dot. You can also make it repeat indefinitely until the connection is established to get cyclic animation.
Another way is to make a SequentialTransition which will have two PauseTransitions of 0.5 seconds.
BTW in your code you pause the main UI thread and that is why you can’t see the animation.

Why does the blue tooth low energy scanner need to be restarted again?

I noticed that in a couple implementations of the ble scanner that the scanning is stopped and started again after a given time period, like every 20 seconds.
Here for example here is a scanner class firing up the scanner in a separate thread. You can see in the start() method that the thread is put to sleep for a period of time, and the scanner is then stopped and restarted:
public class BleScanner extends Thread {
private final BluetoothAdapter bluetoothAdapter;
private final BluetoothAdapter.LeScanCallback mLeScanCallback;
private volatile boolean isScanning = false;
public BleScanner(BluetoothAdapter adapter, BluetoothAdapter.LeScanCallback callback) {
bluetoothAdapter = adapter;
mLeScanCallback = callback;
}
public boolean isScanning() {
return isScanning;
}
public void startScanning() {
synchronized (this) {
isScanning = true;
start();
}
}
public void stopScanning() {
synchronized (this) {
isScanning = false;
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
#Override
public void run() {
try {
// Thread goes into an infinite loop
while (true) {
synchronized (this) {
// If there is not currently a scan in progress, start one
if (!isScanning) break;
bluetoothAdapter.startLeScan(mLeScanCallback);
}
sleep(Constants.SCAN_PERIOD); // Thread sleeps before stopping the scan
// stop scan
synchronized (this) {
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
// restart scan on next iteration of infinite while loop
}
} catch (InterruptedException ignore) {
} finally { // Just in case there is an error, the scan will be stopped
bluetoothAdapter.stopLeScan(mLeScanCallback);
// The finally block always executes when the try block exits. This ensures that the
// finally block is executed even if an unexpected exception occurs.
}
}
}
Are there any benefits to stopping and restarting the scanner? Why not just let the scan continue perpetually?
There are advantages. On some devices, you would only see an advertisement from a device once per scan. On some you would see all advertisements. Also, restarting the scan cleans up some low-level stuff and is generally better than keeping the scanner active all the time.

Java EventListener inside of SwingWorker

OK, so I'm a bit new to SwingWorker in Java.
I've built a Java GUI that, when the "Start" button is pressed, launches several SwingWorker threads. The first thread simply keeps track of run time and updates the GUI appropriately. The second one plays a series of sounds files. The third (and problematic) thread should monitor the serial port for incoming data to be manipulated later on down the road. All of these threads will be running for a while, hence them being SwingWorkers.
I am using the jSSC library (https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_examples) to read data from the serial port, and it does so by firing an eventListener.
My question: Is it redundant/inelegant to code an EventListener inside of a SwingWorker thread? And if so, is there a better way to go about this?
Here is a bit of my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
SerialPort serialPort = findPort(); // returns a serialport I can use to read data from.
SwingWorker worker1 = new SwingWorker<Void, Void>(){
#Override
protected Void doInBackground() throws Exception {
long elapsedTime, startTime = System.currentTimeMillis();
while (true){
Thread.sleep(1000);
elapsedTime = (System.currentTimeMillis() - startTime)/1000;
jTimeField.setText(String.format("%02d:%02d:%02d", elapsedTime/3600, (elapsedTime%3600)/60, elapsedTime%60));
if (isCancelled()){} /* Check if thread has been canceled */
}
}
};
SwingWorker worker2 = new SwingWorker<Void, Void>(){
#Override
protected Void doInBackground() throws Exception {
// This Thread: Plays music files; Self terminates; On termination also terminates worker 1 and 3 via cancel().
}
};
SwingWorker worker3 = new SwingWorker<Void, Void>(){
#Override
protected Void doInBackground() throws Exception {
serialPort.addEventListener(new SerialPortReader());
return null;
}
class SerialPortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
byte buffer[];
if (event.isRXCHAR() && event.getEventValue() > 0){
buffer = serialPort.readBytes();
for (byte b: buffer){
// Do stuff with incoming data
}
}
}
}
};
}
Any and all constructive criticism is appreciated.
It does not do any good to add the event listener in your swingworker thread and then return once that's done. Why not just add the listener from your EDT and, if it takes long to process events, fire off processing threads from there? Listening to events can't be blocking, that would defeat the entire Observer pattern.

Why is that Thread interupt method is not breaking its sleep method?

I have this program below
package com;
public class ThreadDemo implements Runnable {
#Override
public void run() {
while(true)
{
try {
System.out.println("Into sleep");
Thread.sleep(1000000000);
System.out.println("Out of sleep");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String args[]) {
ThreadDemo tD = new ThreadDemo();
Thread t1 = new Thread(tD);
t1.start();
t1.interrupt();
}
}
I have started the Thread , and will call its run method and goes into sleep state for the above specified seconds .
i have called t1.interrupt();
This is the screen shot
My question is that why
1.The Thread is not coming out of sleep state ?
Why Into sleep is printed twice ??
You're in a loop:
You're sleeping
Being interrupted and printing the stack trace
Going back to sleep
Never being interrupted again
So it is "coming out of sleep state" (otherwise you wouldn't see the stack trace) - but you're then calling Thread.sleep again.
If you only want to sleep once, get rid of the loop...
1.The Thread is not comng out of sleep state ?
He actually is but
System.out.println("Out of sleep");
is never executed because when you interrupt Thread.sleep(10000); throws a exception and
e.printStackTrace();
is execute instead

Resources