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

Cách đặt độ ưu tiên (priority) cho thread trong Android

Giới thiệu

Thread có độ ưu tiên từ 1-10. Ví dụ này tạo thread, đặt tên và đặt priority cao nhất (MAX_PRIORITY = 10).

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

Giống ví dụ trước (EditText, Button, TextView).

Bước 3: MainActivity.java - thêm setPriority

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;
    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);

        findViewById(R.id.click).setOnClickListener(v -> runThread());
    }

    private void runThread() {
        final String threadName = edit_query.getText().toString();
        if (threadName.isEmpty()) return;

        t = new Thread(() -> {
            try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
            runOnUiThread(() -> textView.setText("Thread: " + t.getName() + ", Priority: " + t.getPriority()));
        });
        t.setName(threadName);
        t.setPriority(Thread.MAX_PRIORITY); // Đặt ưu tiên cao nhất
        t.start();
    }
}

Chạy ứng dụng

Hiển thị tên thread và priority = 10.

Cách đặt độ ưu tiên (priority) cho thread trong Android