Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách sử dụng nhiều thread (multiple threads) trong Android

Giới thiệu

Ví dụ chạy 2 thread song song: thread 1 lấy tên từ EditText, thread 2 chạy nền 5 giây rồi cập nhật TextView khác.

Bước 1-2: Project & Giao diện

Giao diện có 2 TextView (text, text1).

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText edit_query;
    TextView textView, text1;
    Thread t;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit_query = findViewById(R.id.edit_query);
        textView = findViewById(R.id.text);
        text1 = findViewById(R.id.text1);

        findViewById(R.id.click).setOnClickListener(v -> {
            runThread1();
            runThread2();
        });
    }

    // Thread 1: lấy tên từ EditText
    private void runThread1() {
        final String name = edit_query.getText().toString();
        if (name.isEmpty()) return;

        t = new Thread(() -> {
            try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
            runOnUiThread(() -> textView.setText("Thread 1: " + t.getName()));
        });
        t.setName(name);
        t.setPriority(Thread.MAX_PRIORITY);
        t.start();
    }

    // Thread 2: chạy nền 5 giây
    private void runThread2() {
        new Thread(() -> {
            try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }
            runOnUiThread(() -> text1.setText("Thread 2: tutorialspoint.com"));
        }).start();
    }
}

Chạy ứng dụng

Nhấn nút: Thread 1 hiển thị tên sau 0.5s, Thread 2 hiển thị text cố định sau 5s.

Cách sử dụng nhiều thread (multiple threads) trong Android