The thread you are starting is not doing anything. It starts when you call a.start()
and instantly terminates, because there is no code for this thread to run. Following this, the same thread that started the new one, and that is processing the click event, enters an infinite loop, so your user interface is completely blocked.
You need to give some code for the new thread to execute. To do so, you either pass the thread a Runnable
or you override the thread's run()
method. For example, to give it a Runnable
containing the loop that prints every 2 seconds, you could do:
final Thread a = new Thread(new Runnable() {
@Override public void run() {
while (true) {
try {
Thread.sleep(2000);
System.out.println("code");
} catch (InterruptedException e) {
break;
}
}
}
};
a.start();
After that, if you ever want to stop that thread, you'd need to save a reference to the thread a
in a field or something, and then call a.interrupt()
. This will cause sleep
to throw an InterruptedException
, which will be caught and will execute break
, which terminates the infinite loop and allows the thread to reach the end of the run
method, which terminates the thread.
For example:
private Thread a = null;
... click handler on start button ... {
if (a == null) {
a = new Thread(new Runnable() {
@Override public void run() {
while (true) {
try {
Thread.sleep(2000);
System.out.println("code");
} catch (InterruptedException e) {
break;
}
}
}
};
a.start();
}
}
... click handler on "stop" button ... {
if (a != null) {
a.interrupt();
a = null;
}
}