Java는 synchronized 키워드를 사용해 접근 제어를 한다.
예제 코드 펼치기클래스 하나당 하나의 스레드만 접근 허용
static synchronized T mothod()
public static synchronized void doSomething() {
String threadName = Thread.currentThread().getName();
System.out.println(String.format("%s entered the method", threadName));
System.out.println(String.format("%s leaves the method", threadName));
}
}
```java
Thread-0 entered the method
Thread-0 leaves the method
Thread-1 entered the method
Thread-1 leaves the method
예제 코드 펼치기인스턴스 하나당 하나의 스레드만 접근 허용
synchronized T method()
class SomeClass {
private String name;
public SomeClass(String name) {
this.name = name;
}
public synchronized void doSomething() {
String threadName = Thread.currentThread().getName();
System.out.println(String.format("%s entered the method of %s", threadName, name));
System.out.println(String.format("%s leaves the method of %s", threadName, name));
}
}
SomeClass instance1 = new SomeClass("instance-1");
SomeClass instance2 = new SomeClass("instance-2");
MyThread first = new MyThread(instance1);
MyThread second = new MyThread(instance1);
MyThread third = new MyThread(instance2);
first.start();
second.start();
third.start();
Thread-0 entered the method of instance-1
Thread-2 entered the method of instance-2
Thread-0 leaves the method of instance-1
Thread-1 entered the method of instance-1
Thread-2 leaves the method of instance-2
Thread-1 leaves the method of instance-1
예제 코드 펼치기포함된 블럭의 제어자에 따라 적용됨
// static synchronized synchronized (SomeClass.class) {/*code*/} // instance synchronized synchronized (this) {/*code*/} // object synchronized synchronized (SomethingObject) {/*code*/}
class SomeClass {
static T staticMethod() {
// static synchronized block
synchronized (SomeClass.class) {
// code
}
}
T instanceMethod() {
// instance synchronized block
synchronized (this) {
// code
}
}
}
synchronized(this){} 는 어떤 메서드가 되었든 그 객체 전체를 lock 하기에, 다른 메서드의 접근도 제한됨
따라서, 객체에 있는 메서드를 각각 제어하기 위한 방법이 필요함
메서드마다 lock 객체 생성 후, 각 객체를 lock 하는 방법으로 동기화 제어
class SomeClass {
private int numberOfCallingMethod1 = 0;
private int numberOfCallingMethod2 = 0;
final Object lock1 = new Object(); // an object for locking
final Object lock2 = new Object(); // another object for locking
public void method1() {
System.out.println("method1...");
synchronized (lock1) {
numberOfCallingMethod1++;
}
}
public void method2() {
System.out.println("method2...");
synchronized (lock2) {
numberOfCallingMethod2++;
}
}
}