Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 ArrayBlockingQueue의 poll() 메서드를 사용하는 방법

ArrayBlockingQueue란 무엇인가?

예제를 살펴보기에 앞서 ArrayBlockingQueue에 대해 간단히 알아보겠습니다. ArrayBlockingQueue는 배열 기반으로 구현된 큐로, FIFO(선입선출) 방식으로 동작합니다. 즉, 가장 먼저 삽입된 첫 번째 요소가 가장 오래 큐에 머무르고, 마지막에 삽입된 요소는 가장 짧은 시간 동안만 머무릅니다.

poll() 메서드는 큐의 헤드(head, 맨 앞 요소)를 꺼내어 제거하는 역할을 하며, 큐가 비어 있을 경우 null을 반환합니다. 이 예제에서는 안드로이드에서 ArrayBlockingQueue의 poll() 메서드를 사용하는 방법을 단계별로 살펴보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계 — 레이아웃 파일 수정

res/layout/activity_main.xml에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <TextView
        android:id="@+id/actionEvent"
        android:textSize="40sp"
        android:layout_marginTop="30dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />
</LinearLayout>

위 코드에서는 ArrayBlockingQueue의 요소를 화면에 표시하기 위해 TextView를 하나 배치했습니다.

3단계 — MainActivity 작성

src/MainActivity.java에 다음 코드를 추가합니다.

package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.ArrayBlockingQueue;
public class MainActivity extends AppCompatActivity {
    ArrayBlockingQueue arrayBlockingQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        arrayBlockingQueue = new ArrayBlockingQueue<>(50);
        final TextView actionEvent = findViewById(R.id.actionEvent);
        arrayBlockingQueue.add("sai");
        arrayBlockingQueue.add("ram");
        arrayBlockingQueue.add("krishna");
        arrayBlockingQueue.add("prasad");
        actionEvent.setText("" + arrayBlockingQueue);
        actionEvent.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                actionEvent.setText("" + arrayBlockingQueue.poll());
            }
        });
    }
}

위 코드에서는 용량 50의 ArrayBlockingQueue를 생성한 뒤, 네 개의 문자열 요소를 추가하고 TextView에 큐 전체를 출력합니다. 그리고 TextView를 클릭하면 poll() 메서드가 호출되어 큐의 헤드 요소가 하나씩 꺼내져 화면에 표시됩니다.

애플리케이션 실행

애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바에서 Run(실행) 아이콘을 클릭하고, 옵션 목록에서 본인의 모바일 기기를 선택합니다. 그러면 모바일 기기에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 ArrayBlockingQueue의 poll() 메서드를 사용하는 방법

이제 화면의 TextView를 클릭하면, 아래와 같이 큐의 헤드 요소가 표시되는 것을 확인할 수 있습니다. 클릭할 때마다 다음 요소가 순서대로 꺼내집니다.

안드로이드에서 ArrayBlockingQueue의 poll() 메서드를 사용하는 방법

정리

poll()은 큐가 비어 있어도 예외를 발생시키지 않고 null을 반환한다는 점에서 remove() 메서드와 차이가 있습니다. 따라서 큐가 비어 있을 가능성이 있는 상황에서는 poll()을 사용하는 것이 안전합니다.