I have a class with event method that would often be called. Let’s say the method name is: onClicked. Inside the method, I would create a thread to do some stuffs.
First, I tried by creating a thread object inside the event method. The code is like this:
public class MyService {
//Event method
public void onClick() {
new Thread(new Runnable() {
@Override
public void run() {
// do some stuff here
}
}).start();
}
}
But since the onClick would often be called, I’m worried if the new thread object who created everytime when the event method called would create memory-space or performance issue?
Alternatively, I can create a class member thread solution like this:
public class MyService {
private Thread myThread;
//Event method
public void onClick() {
myThread = new Thread(new Runnable() {
@Override
public void run() {
// do some stuff here
}
});
myThread.start();
}
}
So which code is better? 1st or 2nd? Or is there other better solution?
You can’t use the second code without reinitializing your Thread on each
OnClick(). This is because once a Thread has finished running, it is “dead.” Thus, subsequent calls tostart()will fail and result in anIllegalThreadStateException.It would be better to use the first code, as the GC will remove the Thread after it has completed.