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

Cách lấy số lượng luồng (thread) hiện tại trong Android

Giới thiệu

Thread.activeCount() trả về ước lượng số luồng đang hoạt động trong ThreadGroup của luồng hiện tại. Demo hiển thị số lượng này.

Các bước

Bước 1: Tạo project

File → New Project → Empty Activity.

Bước 2: Layout (activity_main.xml)

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

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

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

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);
        textView.setText("Số luồng hiện tại: " + Thread.activeCount());
    }
}

Giải thích

  • Thread.activeCount(): trả về int, số luồng active trong thread group của luồng gọi (thường là main thread group).
  • Kết quả bao gồm main thread, UI thread, và các thread nền do hệ thống/app tạo.
  • Giá trị thay đổi theo thời gian, chỉ mang tính tham khảo.

Kết quả

Cách lấy số lượng luồng (thread) hiện tại trong Android

Hiển thị "Số luồng hiện tại: 2" (hoặc số khác tùy thiết bị).