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

Android ConcurrentLinkedQueue의 clear() 메서드 사용법 완벽 가이드

ConcurrentLinkedQueue란 무엇인가?

예제를 살펴보기에 앞서 ConcurrentLinkedQueue에 대해 먼저 알아보겠습니다. ConcurrentLinkedQueue는 연결 리스트(linked node) 기반의 무제한(unbounded) 큐입니다. 여러 스레드가 동시에 큐의 요소에 안전하게 접근할 수 있어 멀티스레딩 환경에서 특히 유용합니다.

이 큐는 FIFO(선입선출) 방식으로 동작하며, 새로운 요소는 항상 큐의 꼬리(tail)에서 삽입됩니다. 또한 null 값을 허용하지 않는다는 점도 기억해야 합니다.

이 글에서는 Android의 ConcurrentLinkedQueue에서 clear() 메서드를 사용하여 큐의 모든 요소를 한 번에 삭제하는 방법을 알아봅니다.

구현 단계

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>

위 코드에서는 TextView 하나를 배치하여 ConcurrentLinkedQueue의 요소들을 화면에 표시하도록 구성했습니다.

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) {
             concurrentLinkedQueue.clear();
             actionEvent.setText("" + concurrentLinkedQueue);
          }
       });
    }
}

코드 설명

위 코드의 핵심 흐름은 다음과 같습니다.

먼저 add() 메서드를 사용해 "sai", "ram", "krishna", "prasad", "ram" 다섯 개의 문자열 요소를 큐에 삽입한 후, TextView에 현재 큐의 전체 내용을 출력합니다. 그다음 TextView에 클릭 리스너를 등록하는데, 화면을 클릭하면 clear() 메서드가 호출되어 큐의 모든 요소가 삭제되고, 비워진 큐의 상태(빈 대괄호 [])가 다시 화면에 표시됩니다.

앱 실행 및 결과 확인

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

앱이 실행되면 큐에 담긴 요소들이 다음과 같이 화면에 나타납니다.

Android ConcurrentLinkedQueue의 clear() 메서드 사용법 완벽 가이드

여기서 TextView를 클릭하면 clear() 메서드에 의해 모든 요소가 삭제된 결과를 확인할 수 있습니다.

Android ConcurrentLinkedQueue의 clear() 메서드 사용법 완벽 가이드

정리

이처럼 ConcurrentLinkedQueue의 clear() 메서드를 활용하면 스레드 안전성을 유지하면서 큐의 모든 요소를 손쉽게 삭제할 수 있습니다. 멀티스레드 환경에서 큐 데이터를 초기화해야 하는 상황이라면 이 예제를 참고해 보시기 바랍니다.