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

Android ConcurrentLinkedDeque에서 pollFirst() 메서드 활용법

ConcurrentLinkedDeque란 무엇인가?

예제를 살펴보기 전에 ConcurrentLinkedDeque에 대해 먼저 알아보겠습니다. ConcurrentLinkedDeque는 연결 노드(linked nodes) 기반의 무제한(unbounded) 덱(Deque) 자료구조입니다. 여러 스레드가 동시에 접근하더라도 안전하게 덱의 요소를 처리할 수 있도록 설계되어 있어, 멀티스레딩 환경에서 매우 유용합니다.

이 글에서는 Android에서 ConcurrentLinkedDeque의 pollFirst() 메서드를 사용하는 방법을 단계별로 알아보겠습니다.

구현 단계

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>

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

3단계: MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.ConcurrentLinkedDeque;
public class MainActivity extends AppCompatActivity {
    ConcurrentLinkedDeque concurrentLinkedDeque;
    String head;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        concurrentLinkedDeque = new ConcurrentLinkedDeque<String>();
        final TextView actionEvent = findViewById(R.id.actionEvent);
        concurrentLinkedDeque.add("sai");
        concurrentLinkedDeque.add("ram");
        concurrentLinkedDeque.add("krishna");
        concurrentLinkedDeque.add("prasad");
        actionEvent.setText("" + concurrentLinkedDeque);
        actionEvent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                concurrentLinkedDeque.pollFirst();
                actionEvent.setText("" + concurrentLinkedDeque);
            }
        });
    }
}

코드 동작 원리

위 코드의 핵심 로직은 다음과 같습니다.

  • 요소 추가: add() 메서드를 통해 "sai", "ram", "krishna", "prasad" 네 개의 문자열을 덱에 순서대로 삽입합니다.
  • pollFirst() 호출: TextView를 클릭하면 pollFirst()가 실행되어 덱의 첫 번째(head) 요소를 제거하고 반환합니다. 만약 덱이 비어 있다면 null을 반환하며 예외를 발생시키지 않습니다.
  • 화면 갱신: 요소가 제거된 후 갱신된 덱의 내용을 TextView에 다시 표시합니다.

애플리케이션 실행 및 결과 확인

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

Android ConcurrentLinkedDeque에서 pollFirst() 메서드 활용법

이제 화면의 TextView를 클릭하면 pollFirst()에 의해 첫 번째 요소가 제거되어 아래와 같은 결과가 나타납니다.

Android ConcurrentLinkedDeque에서 pollFirst() 메서드 활용법

마무리

이처럼 pollFirst() 메서드를 사용하면 ConcurrentLinkedDeque의 맨 앞 요소를 손쉽게 제거할 수 있습니다. 덱이 비어 있는 경우에도 예외 없이 null을 반환하기 때문에, 멀티스레드 환경에서 안전하게 큐 처리 로직을 구현할 때 특히 유용합니다.