Java – Is it safe to use Java threads in the same way as desktop applications?

Is it safe to use Java threads in the same way as desktop applications?… here is a solution to the problem.

Is it safe to use Java threads in the same way as desktop applications?

Android must manage threads, or you can use code like this:

public class GameThread implements Runnable {

public void run() {
        while (!finished) {

game work

try {
                Thread.sleep(fps);
            } catch (InterruptedException e) {
                 Interruptions here are no big deal.
            }
        }
    } 
}

Solution

You can use Thread directly, but there are some issues in Android

  • Do not block the UI thread
  • Do not access the Android UI toolkit from outside the UI thread

About Processes and Threads for Android The documentation provides sufficient guidance to help you get started.

Use AsyncTask

AsyncTask allows you to perform asynchronous work on your user
interface. It performs the blocking operations in a worker thread and
then publishes the results on the UI thread, without requiring you to
handle threads and/or handlers yourself.

Related Problems and Solutions