본문 바로가기
JAVA/응용문제

[Thread] 멀티쓰레드, 배열, 쓰레드 이용해서 int list 처리

by java나유 2022. 7. 13.

아래는 쓰레드를 한번만 실행해서 푼 문제이고요.

	public static void main(String[] args) {

		/*	다음 숫자 배열이 있습니다.
		 	해당 배열 값을 짝수, 홀수 값을 각각 가져와서
		 	배열로 처리합니다.
		 	결과 : 짝수 : [2,6,10,22,42,50]
		 	        홀수 : [1,7,11,15,43,51]
		 	멀티 쓰레드를 이용하여 출력합니다
		*/
		cal ca = new cal();
		ca.start();
		
	}
}

class cal extends Thread {
	
	Integer arr[] = {1,2,6,7,10,11,15,22,42,43,50,51};
	ArrayList<Integer> even = new ArrayList<>();
	ArrayList<Integer> odd = new ArrayList<>();
	
	public cal(Integer[] a) {
		this.arr = a;
	}
	public cal() {
		
		int ea = this.arr.length; //12
		
		for(int f = 0; f < ea; f++) {
			if(this.arr[f] %2 == 0) {
				
				this.even.add(arr[f]);
			}
			else {
				this.odd.add(arr[f]);
			}
		}
	}

	@Override
	public void run() {
	
		System.out.println("짝수 : " + this.even);
		System.out.println("홀수 : " + this.odd);
	}
}

 

 

아래는 배열을 푸는 것을 멀티쓰레드로 푼 풀이입니다!

 

import java.awt.List;
import java.util.ArrayList;

public class array {

	public static void main(String[] args) {
		// 해당 배열값을 짝수, 홀수 값을 가져와서 배열로 처리합니다.
		// 결과
		// 짝수 결과:[2,6,10,22,42,50]
		// 홀수 결과:[1,7,11,15,43,51]
		// 멀티쓰레드 이용해서 출력합니다.

		int number[] = { 1, 2, 6, 7, 10, 11, 15, 22, 42, 43, 50, 51 };
		plusbox pb = null;

		for (int i = 0; i < number.length; i++) {
			pb = new plusbox(number[i]);
		}
		pb.start();
	}
}

class plusbox extends Thread {
	int num;

	static ArrayList<Integer> even = new ArrayList<>();
	static ArrayList<Integer> odd = new ArrayList<>();

	public plusbox(int no) {
		this.num = no;
		// System.out.println(this.num);

		if (this.num % 2 != 0) {
			odd.add(this.num);
			// ck=true;
			// continue;
		} else {
			even.add(this.num);
		}
	}
	@Override
	public void run() {
		System.out.println(odd);
		System.out.println(even);
	}

}

728x90

댓글