There is a task: to start a thread (Thread1) 1 time and only. At the same time, another thread (Thread2) periodically creates the desired thread (Thread1). Due to the inability to control the amount, the action is repeated. How to solve beautifully and correctly, I do not know.
Main question. We have
static Thread myThread; @Override public void run() { if (myThread != null) { if (isAlive()) { // Если поток есть, и живой, то return. // Т.е. получается поток создался, // но не делая ничего завершился, // а предыдущий, который еще работает.... дорабатывает. return; } } // Если не было return, то поток работает } But, I'm worried that the following will happen: in the stream, the code is executed in while (true) {}, i.e. constantly. On android. And if due to the lack of memory or other OS reasons, it will beat my thread (Thread1), then another thread (Thread2) creates it again. The code above occurs, and if static Thread myThread is not reset, then the result will not work and the others will not be able to start work. The onDestroy method is not available for Thread, not for the Runnable interface.
Perhaps I suggested a very "ugly" decision and it is done quite differently, if anyone knows, tell me which direction to look. I do not quite understand the nature of the work of the garbage collector in java, and the policies of the Android OS (the reasons for terminating the process abnormally, etc.).
PS A question in short: 1 stream must live or not one. If none, be able to run 1.
UDP: This code seems to work, I do not know how it will behave in non-standard situations.
public static Thread myThread; @Override public int onStartCommand(Intent intent, int flags, int startId) { if (myThread == null) { myThread = new Thread(new TaskExecutor(this)); myThread.start(); } else { if (!myThread.isAlive()) { myThread = new Thread(new TaskExecutor(this)); myThread.start(); } } return START_STICKY; } The first option that I wrote there for some reason this.isAlive () does not work within the stream already. Returns false;
UPD 2: Eugene Krivenja, the answer is good. But Creating a stream when recreating a service is as follows: The old service was created, created a stream. Then the Service dies (I nailed it myself), but the stream is functioning. Service re-created, creates a thread - we have 2 workflows that duplicate actions. The static variable solved my problem, but as you said, there may be unexplained actions. I will think further on how to make 100% safe.