동기화 synchronized(this) 코드 블록이 현재 대상을 잠그는 것을 검증합니다 (synchronized 방법과 마찬가지로synchronized(this)도 현재 대상을 잠그는 것입니다)

synchronized 방법과 마찬가지로synchronized(this)도 현재 대상을 잠그는 것입니다

package mytask;
public class Task {
	synchronized public void otherMethod() {
		System.out.println("------------------------run--otherMethod");
	}
	public void doLongTimeTask() {
		synchronized (this) {
			for (int i = 0; i < 10000; i++) {
				System.out.println("synchronized threadName="
						+ Thread.currentThread().getName() + " i=" + (i + 1));
			}
		}
	}
}
package mythread;
import mytask.Task;
public class MyThread1 extends Thread {
	private Task task;
	public MyThread1(Task task) {
		super();
		this.task = task;
	}
	@Override
	public void run() {
		super.run();
		task.doLongTimeTask();
	}
}
package mythread;
import mytask.Task;
public class MyThread2 extends Thread {
	private Task task;
	public MyThread2(Task task) {
		super();
		this.task = task;
	}
	@Override
	public void run() {
		super.run();
		task.otherMethod();
	}
}
package test;
import mytask.Task;
import mythread.MyThread1;
import mythread.MyThread2;
public class Run {
	public static void main(String[] args) throws InterruptedException {
		Task task = new Task();
		MyThread1 thread1 = new MyThread1(task);
		thread1.start();
		Thread.sleep(100);
		MyThread2 thread2 = new MyThread2(task);
		thread2.start();
	}
}

결실
synchronized threadName=Thread-0 i=1
synchronized threadName=Thread-0 i=2
synchronized threadName=Thread-0 i=3
synchronized threadName=Thread-0 i=4
synchronized threadName=Thread-0 i=5
synchronized threadName=Thread-0 i=6
synchronized threadName=Thread-0 i=7
synchronized threadName=Thread-0 i=8
synchronized threadName=Thread-0 i=9
synchronized threadName=Thread-0 i=10
Thread-1run--otherMethod

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

좋은 웹페이지 즐겨찾기