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

Cách lấy tên thread hiện tại trong Android

Giới thiệu

Mỗi thread có tên. Thread chính mặc định tên là "main". Ví dụ này lấy tên thread hiện tại.

Bước 1: Tạo project mới

Android Studio → File → New Project.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_marginTop="100dp"
    tools:context=".MainActivity">

    <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

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

public class MainActivity extends AppCompatActivity {
    TextView textView;

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

        textView = findViewById(R.id.text);
        // toString() của Thread trả về "Thread[,,]"
        textView.setText("Thread hiện tại: " + Thread.currentThread());
    }
}

Chạy ứng dụng

Hiển thị thông tin thread chính: "Thread[main,5,main]".

Cách lấy tên thread hiện tại trong Android