synchronized mehtod
의 경우 동일한 인스턴스에 대하여 synchronized
가 붙은 메서드를 모두 동일한 락을 걸어버린다.synchronized block
이다.by this
public class D {
public void run(String name) {
// 전처리 로직
// 인스턴스의 블락 단위로 락을 건다
// 동기화 시작
synchronized (this) {
System.out.println(name+" lock");
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+" unlock");
}
// 동기화 해제
// 후처리 로직
}
public void print(String name) {
System.out.println(name+" hello");
}
}
by instance of B
public class A {
B b = new B();
public void run(String name) {
synchronized (b) {
System.out.println(name+" lock");
b.run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+" unlock");
}
}
public synchronized void print(String name) {
System.out.println(name + " hello");
}
}
public class Main {
private static void synchronizedBlockDifferentInstance() {
D d1 = new D();
D d2 = new D();
Thread thread1 = new Thread(() -> {
d1.run("thread1");
});
Thread thread2 = new Thread(() -> {
d2.run("thread2");
});
thread1.start();
thread2.start();
}
}
public class Main {
private static void synchronizedBlock() {
D d = new D();
Thread thread1 = new Thread(() -> {
d.run("thread1");
});
Thread thread2 = new Thread(() -> {
d.run("thread2");
});
thread1.start();
thread2.start();
}
}
public class Main {
private static void synchronizedAndNonSynchronized() {
D d = new D();
Thread thread1 = new Thread(() -> {
d.run("thread1");
});
Thread thread2 = new Thread(() -> {
d.print("thread2");
});
thread1.start();
thread2.start();
}
}
public class Main {
public static void synchronizedBlockByInstance() {
A a = new A();
Thread thread1 = new Thread(() -> {
a.run("thread1");
});
Thread thread2 = new Thread(() -> {
a.run("thread2");
});
Thread thread3 = new Thread(() -> {
a.print("자원 B와 관련 없는 thread3");
});
thread1.start();
thread2.start();
thread3.start();
}
}
thread1
과 thread2
는 동기화가 된다(b). 하지만 thread3
는 동기화 되지 않는다(this).public class E {
public void run(String name) {
synchronized (B.class) {
System.out.println(name+" lock");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+" unlock");
}
}
}
public class Main {
public static void synchronizedBlockByClass() {
// E e = new E();
E e1 = new E();
E e2 = new E();
Thread thread1 = new Thread(() -> {
e1.run("thread1");
});
Thread thread2 = new Thread(() -> {
e2.run("thread2");
});
thread1.start();
thread2.start();
}
}
클래스 인자
public class F {
public static void run(String name) {
synchronized (B.class) {
System.out.println(name + " lock");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " unlock");
}
}
}
정적 인스턴스 인자
public class F {
static B b = new B();
public static void run(String name) {
synchronized (b) {
System.out.println(name + " lock");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " unlock");
}
}
}