1 분 소요

메소드 단위의 동기화의 문제점

  • 동기화의 범위 정하기

임계영역을 정할 때 성능에 대한 문제가 발생한다

자기가 쓰고자하는 곳만 lock을 걸면되는데 더 큰 영역의 lock을 걸면 기다리는 스레드가 많아진다

메소드 단위로 동기화를 할 경우 임계영역이 커진다

  • 타임스탬프로 확인하기
package part2;

import java.sql.Timestamp;

public class Proagram2 {

	public static void main(String[] args) {
		Timestamp time1 = new Timestamp(System.currentTimeMillis());
		System.out.println(time1);

		CharList list = new CharList();

		Runnable subMain = new Runnable() {

			@Override
			public void run() {
				// 하나의 값만 출력하기 때문에
				for (int i = 0; i < 80; i++)
					list.printNext();
			}
		};
		// 스레드 그룹

		Thread th1 = new Thread(subMain);
		th1.setName("sub1");

		Thread th2 = new Thread(subMain);
		th2.setName("sub2");

		th1.start(); // 꼭 있어야 한다
		th2.start(); // 꼭 있어야 한다

		Thread th = Thread.currentThread();
		th.setName("Main");

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {

			e.printStackTrace();

		}
		try {
			th1.join();
			th2.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Timestamp time2 = new Timestamp(System.currentTimeMillis());
		System.out.println(time2.getTime() - time1.getTime());

		System.out.println("=====exit=====");

	}
}
  • 메소드 단위의 동기화를 실행 할 경우

sub1[14] : index:153, char: ?
sub1[14] : index:154, char: ?
sub1[14] : index:155, char: ?
sub1[14] : index:156, char: ?
sub1[14] : index:157, char: ?
sub1[14] : index:158, char: ?
sub1[14] : index:159, char: ?
3936
  • 임계영역을 자기가 쓸곳의 영역에 지정 할 경우
sub2[15] : index:152, char: ?
sub1[14] : index:153, char: ?
sub2[15] : index:154, char: ?
sub1[14] : index:155, char: ?
sub2[15] : index:156, char: ?
sub1[14] : index:157, char: ?
sub2[15] : index:158, char: ?
sub1[14] : index:159, char: ?
2471

자기가 쓸 공간의 영역을 지정 할시 더욱 시간이 줄어든다

  • 열쇠

락을 열고 푸는것이 중요하지 열쇠를 무엇으로 사용하는지는 상관없다

private Object indexLock; //indexLock을 키로 사용하기

	public CharList() {
		indexLock = new Object();
		list = new char[160]; 
		for (int i = 0; i < 160; i++)
			list[i] = (char) i;

		index = 0;
	}

	public void printNext() {
		Thread th = Thread.currentThread();

		char ch = list[index];

		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			return;
		}

		synchronized (indexLock) { //indexLock 키로 만들기

	
			System.out.printf("%s[%d] : index:%d, char: %c\n", th.getName(), th.getId(), index, list[index]);

			index++; 

		}
	}
}

카테고리:

업데이트:

댓글남기기