Sobes.tech
Middle

Kuidas luua voogu Androidis?

sobes.tech AI

Vastus AI-lt

In Android, you can create threads in the following ways:

  • Inheriting from Thread:

    // Class inheriting from Thread
    class MyThread extends Thread {
        @Override
        public void run() {
            // Code for the task executed in the new thread
            System.out.println("Thread created by inheriting from Thread");
        }
    }
    // Creating and starting the thread
    MyThread myThread = new MyThread();
    myThread.start();
    
  • Implementing the Runnable interface:

    // Class implementing Runnable
    class MyRunnable implements Runnable {
        @Override
        public void run() {
            // Code for the task executed in the new thread
            System.out.println("Thread created by implementing Runnable");
        }
    }
    // Creating a thread with Runnable
    Thread thread = new Thread(new MyRunnable());
    thread.start();
    
  • Using AsyncTask (deprecated): for executing background operations and updating UI.

  • Using HandlerThread: a special class of Thread with Looper and Handler, which simplifies message queue handling in the background.

    // Creating HandlerThread
    HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
    handlerThread.start();
    // Getting Looper
    Looper looper = handlerThread.getLooper();
    // Creating Handler associated with Looper
    Handler handler = new Handler(looper);
    // Sending a task to the thread's queue
    handler.post(new Runnable() {
        @Override
        public void run() {
            // Code for the task executed in handlerThread
            System.out.println("Thread created using HandlerThread");
        }
    });
    
  • Using ExecutorService and ThreadPoolExecutor: to manage thread pools.

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    // Creating a fixed size thread pool
    ExecutorService executor = Executors.newFixedThreadPool(2);
    // Submitting a task for execution
    executor.execute(new Runnable() {
        @Override
        public void run() {
            // Code for the task executed in one of the pool's threads
            System.out.println("Thread created using ExecutorService");
        }
    });
    // Shutting down the pool (important to prevent leaks)
    executor.shutdown();
    
  • Using Kotlin coroutines: a modern approach for asynchronous programming in Android.

    import kotlinx.coroutines.*
    
    // Launching a coroutine in the background
    GlobalScope.launch(Dispatchers.IO) {
        // Code for the task executed in the background (IO) thread
        println("Thread created using coroutines")
    }