본문 바로가기

자바

33. 싱크로나이즈

Synchronized는 하나의 인스턴스에서 n개의 스레드가 진행될 경우 객체의 선언되어 있는 인스턴스변수를 스레드가 공유하게 되어 인스턴스 값에 영향을 미치는 것을 방지하기 위해 나온 키워드이다. Synchronized를 이용하면 먼저 수행되는 스레드의 모든 작업이 끝날때 까지 다른 스레드가 기다려야 한다.

package com.Synchronized;

public class HowToUseSynchrnoized implements Runnable {
	int testNum = 0;
	@Override
	public synchronized void run() { //synchronzied를 이용하여 스레드의 우선 순위를 정한다.
		for(int i = 0; i < 10; i++) {
			if(Thread.currentThread().getName().equals("A")) {
				System.out.println("----------------------------------");
				testNum++;
			}
			System.out.println("Thread Name : " + Thread.currentThread().getName() + ", test Num : " + testNum);
			try {
				Thread.sleep(500);
			} 
			catch (Exception e) {}
		}

	}
}

 

package com.Synchronized;

public class MainClass {
	public static void main(String[] args) {
		HowToUseSynchrnoized hs = new HowToUseSynchrnoized();
		
		Thread thread0 = new Thread(hs, "A");
		Thread thread1 = new Thread(hs, "B");
		thread0.start();
		thread1.start();
		
		System.out.println(Thread.currentThread().getName());
		System.out.println("Main");
		
	}

'자바' 카테고리의 다른 글

32. 쓰레드  (0) 2019.08.21
31. Java 입출력(I/O)  (0) 2019.08.19
30. Java Collection2  (0) 2019.08.14
29. Java collection1  (0) 2019.08.12
28. 예외 처리  (0) 2019.08.11