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

안드로이드 ConcurrentLinkedQueue에서 size() 메서드를 사용하는 방법

ConcurrentLinkedQueue란?

예제를 살펴보기 전에 먼저 ConcurrentLinkedQueue가 무엇인지 간단히 알아보겠습니다. ConcurrentLinkedQueue는 연결 노드(linked nodes) 기반의 크기 제한이 없는(unbounded) 큐입니다. 여러 스레드가 동시에 큐에 접근하더라도 안전하게 요소를 처리할 수 있도록 설계되어 있으며, 요소는 FIFO(선입선출) 방식으로 관리되고 새로운 요소는 항상 큐의 꼬리(tail)에 추가됩니다. 또한 null 값은 허용되지 않습니다.

이번 예제는 안드로이드에서 ConcurrentLinkedQueue의 size()를 활용하는 방법을 보여줍니다.

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>

위 코드에서는 ConcurrentLinkedQueue의 요소를 화면에 표시하기 위해 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.ConcurrentLinkedQueue;
public class MainActivity extends AppCompatActivity {
   ConcurrentLinkedQueue concurrentLinkedQueue;
   String head;
   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      concurrentLinkedQueue = new ConcurrentLinkedQueue<String>();
      final TextView actionEvent = findViewById(R.id.actionEvent);
      concurrentLinkedQueue.add("sai");
      concurrentLinkedQueue.add("ram");
      concurrentLinkedQueue.add("krishna");
      concurrentLinkedQueue.add("prasad");
      concurrentLinkedQueue.add("ram");
      actionEvent.setText("" + concurrentLinkedQueue);
      actionEvent.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            actionEvent.setText("" +concurrentLinkedQueue.isEmpty());
         }
      });
   }
}

코드를 살펴보면, 먼저 문자열을 담을 수 있는 ConcurrentLinkedQueue 인스턴스를 생성하고 add() 메서드로 여러 요소를 추가한 뒤, TextView에 큐 전체를 출력합니다. 그리고 TextView를 클릭하면 isEmpty() 호출 결과가 화면에 표시되도록 클릭 리스너를 등록했습니다.

앱 실행 및 결과 확인

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

안드로이드 ConcurrentLinkedQueue에서 size() 메서드를 사용하는 방법

이제 화면의 TextView를 클릭하면 아래와 같은 결과가 나타납니다.

안드로이드 ConcurrentLinkedQueue에서 size() 메서드를 사용하는 방법

참고: size() 메서드 활용 팁

ConcurrentLinkedQueue는 현재 저장된 요소의 개수를 반환하는 size() 메서드도 함께 제공합니다. 다만 이 큐는 내부적으로 노드를 순회하며 개수를 계산하기 때문에, 데이터가 많을 경우 성능 비용이 커질 수 있습니다. 따라서 단순히 큐가 비어 있는지만 확인하고 싶다면 위 예제처럼 isEmpty()를 사용하는 것이 더 효율적이며, 정확한 개수가 필요한 경우에만 size()를 호출하는 것이 좋습니다.