스레드synchronized 블록

2915 단어
① 같은 대상의 두 스레드
package co.test.synchronize;

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

public class CopyOfTest implements Runnable {
	private List<String> list = new ArrayList<String>();
	private int count = 0;

	public CopyOfTest(int whichThread) {
		count = whichThread;
	}

	public static void main(String[] args) {
		//  -----------------------↓
		CopyOfTest test = new CopyOfTest(0);

		Thread thread1 = new Thread(test);
		thread1.start();
		Thread thread2 = new Thread(test);
		thread2.start();
		//  -----------------------↑
	}

	@Override
	public void run() {
		if (count == 0) {
			function3();
		} else {
			function4();
		}
	}

	private void function3() {
		count = 1;
		synchronized (list) {
			System.out.println("function33333 is start");
			try {
				//  
				Thread.sleep(3000);
				list.add("bb");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("function33333 is end");
		}
	}

	private void function4() {
		synchronized (list) {
			System.out.println("function44444 is start");
			System.out.println("list :" + list.size());
			System.out.println("function44444 is end");
		}
	}
}

실행 결과:
function33333 is start
function33333 is end
function44444 is start
list :1
function44444 is end

function 4 는 function 3 이 실행된 후에야 실행됩니다
② 두 객체 중 두 스레드
package co.test.synchronize;

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

public class CopyOfTest implements Runnable {
	private List<String> list = new ArrayList<String>();
	private int count = 0;

	public CopyOfTest(int whichThread) {
		count = whichThread;
	}

	public static void main(String[] args) {
		//  -----------------------↓
		CopyOfTest test1 = new CopyOfTest(0);
		CopyOfTest test2 = new CopyOfTest(1);

		Thread thread1 = new Thread(test1);
		thread1.start();
		Thread thread2 = new Thread(test2);
		thread2.start();
		//  -----------------------↑
	}

	@Override
	public void run() {
		if (count == 0) {
			function3();
		} else {
			function4();
		}
	}

	private void function3() {
		count = 1;
		synchronized (list) {
			System.out.println("function33333 is start");
			try {
				//  
				Thread.sleep(3000);
				list.add("bb");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("function33333 is end");
		}
	}

	private void function4() {
		synchronized (list) {
			System.out.println("function44444 is start");
			System.out.println("list :" + list.size());
			System.out.println("function44444 is end");
		}
	}
}

실행 결과:
function33333 is start
function44444 is start
list :0
function44444 is end
function33333 is end

function3과 function4가 실행 중입니다

좋은 웹페이지 즐겨찾기