SyncJava의 동시화? 메소드, 블록, 정적 유형

Synchronization in Java?

자바에서는 synchronization refers to the ability to control the access of multiple threads to any shared resource. It is an ideal option where we want to allow only one thread to access the shared resource.

This approach of execution is usually referred to as `asynchronous` programming. There are also threads on these processors, which are lightweight processes that can execute instructions simultaneo우습게.

유형 Sync정시화

두 종류의가 있습니다 synchronization methods in Java:

1) 방법 sync정시화

2) Thread sync정시화.

Thread를 공부해보자 방법 sync정시화 상세히.

방법 sync동기화: 그것은 관리합니다 synchronization between programs. For example, programs such as `Microsoft Word`와 `Acrobat reader`는 개별 프로세스로 실행됩니다.

Thread sync동기화: The concurrent execution of the critical resource by two or more Threads is termed Thread Synchronization. You can be grouped further to mutually exclusive` and inter-thread communication.

Java의 잠금이란 무엇입니까?

Java의 잠금은 모니터 또는 잠금으로 알려진 내부 엔터티를 중심으로 구축됩니다. 모든 객체에는 연관된 잠금이 있습니다. 따라서 개체 필드에 대한 일관된 액세스가 필요한 스레드는 개체 필드에 액세스하기 전에 개체 잠금을 획득해야 하며 작업이 완료되면 잠금을 해제합니다. 이렇게 하면 한 번에 하나의 스레드만 공유 데이터에 액세스할 수 있습니다.

Multithreaded program with sync정시화

멀티스레드 프로그램 is a method or block protected from interference from other threads sharing the same resource indicated using the `synchronized` keyword.

사용법 - synchronized method

Any method that is declared as synchronized is known as a synchronized Method. It is also used to lock an object for any shared resource. So, when a thread invokes a synchronized method. It automatically takes possession of the lock for that object and releases it when it has finished its task.

참고 : synchronized keyword cannot work with classes and variables. Only methods and blocks can be used with the keyword.

왜 사용 Synchronized Method?

  • 공유 리소스에 대한 개체를 잠그는 데 사용됩니다.
  • The object gets the lock whenever the synchronized method is called.
  • 스레드가 해당 기능을 완료할 때까지 잠금이 해제되지 않습니다.

구문 :

Acess_modifiers synchronized return_type method_name (Method_Parameters) {
}
class MathService {
    synchronized void getSumOfArray(int[] numbers) {
     int sum = 0;

         for (int number : numbers) {
             System.out.println(Thread.currentThread()
                     .getName()
                     + " adds "
                     + sum + " to "
                     + number + " to get -> "
                     + (sum += number));

             try {
                 Thread.sleep(500);
             } catch (InterruptedException e) {
                 throw new RuntimeException(e);
             }
         }
    }
}
public class Synchronization {
    public static void main(String[] args) {
        MathService mathService = new MathService();

        Thread threadOne = new Thread(() ->
                mathService.getSumOfArray(new int[]{10, 11, 12}));
        Thread threadTwo = new Thread(() ->
                mathService.getSumOfArray(new int[]{20, 21, 22}));

        threadOne.start();
        threadTwo.start();
    }
}

코드 설명:

이 예제를 실행하고 '0' 스레드가 먼저 'mathService' 개체의 잠금을 가져오고 실행이 완료될 때까지 이 잠금을 독점적으로 사용하는 것을 관찰하세요. 이 코드에서는 스레드 '0'과 '1'이 인터리브되지 않습니다. 출력은 아래와 같습니다.

출력:

Thread-0 adds 0 to 10 to get -> 10
Thread-0 adds 10 to 11 to get -> 21
Thread-0 adds 21 to 12 to get -> 33
Thread-1 adds 0 to 20 to get -> 20
Thread-1 adds 20 to 21 to get -> 41
Thread-1 adds 41 to 22 to get -> 63

를 사용하여 synchronized block

Let’s assume that you don’t want to synchronize the entire method. Instead, you want to synchronize a few lines of code. At that time, the Synchronized block helped to synchronize that selected Java code.

Synchronized method locks are accessed on the method, whereas synchronized block locks are accessed on the object.

class MathService {
    void getSumOfArray(int[] numbers) {
        synchronized (this){
            int sum = 0;

            for (int number : numbers) {
                System.out.println(Thread.currentThread()
                        .getName()
                        + " adds "
                        + sum + " to "
                        + number + " to get -> "
                        + (sum += number));

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
public class Synchronization {
    public static void main(String[] args) {
        MathService mathService = new MathService();

        Thread threadOne = new Thread(() ->
                mathService.getSumOfArray(new int[]{10, 11, 12}));
        Thread threadTwo = new Thread(() ->
                mathService.getSumOfArray(new int[]{20, 21, 22}));

        threadOne.start();
        threadTwo.start();
    }
}

코드 설명 :

이 코드를 실행하면 아무런 간섭 없이 작동하는 것을 확인할 수 있습니다.

. synchronized method, the lock is applied by the method, but in the synchronized block, the lock is applied by the object.

출력이 아래와 같은지 확인합니다.

출력:

Thread-0 adds 0 to 10 to get -> 10
Thread-0 adds 10 to 11 to get -> 21
Thread-0 adds 21 to 12 to get -> 33
Thread-1 adds 0 to 20 to get -> 20
Thread-1 adds 20 to 21 to get -> 41
Thread-1 adds 41 to 22 to get -> 63

코드 설명:

When you run this code, you will note that it works without interference, which is what we expected. In the synchronized method, the lock is applied by the method, but in the synchronized block method, the lock is applied by the object.

Using static sync정시화

자바에서 synchronization, if there is more than one object, two threads may acquire the locks and enter a synchronized block or block, with a separate lock for each object. To avoid this, static synchronization can be used.

Synchronized keywords will be used before static methods.

참고 : 정적에서 synchronization, lock access is on the class, not the object and method.

여러 객체 잠금 문제를 보여주는 코드

class MathService {
    synchronized void getSumOfArray(int[] numbers) {
            int sum = 0;

            for (int number : numbers) {
                System.out.println(Thread.currentThread()
                        .getName()
                        + " adds "
                        + sum + " to "
                        + number + " to get -> "
                        + (sum += number));

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
    }
}
public class Synchronization {
    public static void main(String[] args) {
        MathService mathService = new MathService();
        MathService mathService1 = new MathService();

        Thread threadOne = new Thread(() ->
                mathService.getSumOfArray(new int[]{10, 11, 12}));
        Thread threadTwo = new Thread(() ->
                mathService.getSumOfArray(new int[]{20, 21, 22}));
        Thread threadThree = new Thread(() ->
                mathService1.getSumOfArray(new int[]{10, 11, 12}));
        Thread threadFour = new Thread(() ->
                mathService1.getSumOfArray(new int[]{20, 21, 22}));

        threadOne.start();
        threadTwo.start();
        threadThree.start();
        threadFour.start();
    }
}

코드 설명:

'MathService'의 또 다른 인스턴스를 만들 때 스레드가 두 개체와 인터리브되므로 스레드에 간섭이 발생합니다. '0' 스레드와 '2' 스레드는 두 개체와 인터리브되고, 스레드 '1'과 '3'은 두 개체와 인터리브됩니다.

출력:

Thread-0 adds 0 to 10 to get -> 10
Thread-2 adds 0 to 10 to get -> 10
Thread-0 adds 10 to 11 to get -> 21
Thread-2 adds 10 to 11 to get -> 21
Thread-0 adds 21 to 12 to get -> 33
Thread-2 adds 21 to 12 to get -> 33
Thread-1 adds 0 to 20 to get -> 20
Thread-3 adds 0 to 20 to get -> 20
Thread-1 adds 20 to 21 to get -> 41
Thread-3 adds 20 to 21 to get -> 41
Thread-1 adds 41 to 22 to get -> 63
Thread-3 adds 41 to 22 to get -> 63

Same code using synchronized static method

class MathService {
    synchronized static void getSumOfArray(int[] numbers) {
            int sum = 0;

            for (int number : numbers) {
                System.out.println(Thread.currentThread()
                        .getName()
                        + " adds "
                        + sum + " to "
                        + number + " to get -> "
                        + (sum += number));

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
    }
}
public class Synchronization {
    public static void main(String[] args) {
        MathService mathService = new MathService();
        MathService mathService1 = new MathService();

        Thread threadOne = new Thread(() ->
                mathService.getSumOfArray(new int[]{10, 11, 12}));
        Thread threadTwo = new Thread(() ->
                mathService.getSumOfArray(new int[]{20, 21, 22}));
        Thread threadThree = new Thread(() ->
                mathService1.getSumOfArray(new int[]{10, 11, 12}));
        Thread threadFour = new Thread(() ->
                mathService1.getSumOfArray(new int[]{20, 21, 22}));

        threadOne.start();
        threadTwo.start();
        threadThree.start();
        threadFour.start();
    }
}

위의 코드를 실행하고 이제 스레드 간섭이 제거되었음을 확인하세요. 코드의 출력은 아래와 같습니다.

출력:

Thread-0 adds 0 to 10 to get -> 10
Thread-0 adds 10 to 11 to get -> 21
Thread-0 adds 21 to 12 to get -> 33
Thread-3 adds 0 to 20 to get -> 20
Thread-3 adds 20 to 21 to get -> 41
Thread-3 adds 41 to 22 to get -> 63
Thread-2 adds 0 to 10 to get -> 10
Thread-2 adds 10 to 11 to get -> 21
Thread-2 adds 21 to 12 to get -> 33
Thread-1 adds 0 to 20 to get -> 20
Thread-1 adds 20 to 21 to get -> 41
Thread-1 adds 41 to 22 to get -> 63

사용의 장점 sync정시화

동시 애플리케이션으로 작업할 때의 이점은 다음과 같습니다.

  • 의 주요 목적은 synchronization in Java is to prevent inconsistent data by preventing thread interference.
  • synchronized keyword in Java provides locking, which ensures mutually exclusive access to the shared resource and prevents data race.
  • 또한 코드 명령문의 순서가 바뀌는 것을 방지합니다. 컴파일러, which can cause a subtle concurrent issue if we don’t use volatile or synchronized keywords.
  • Synchronized keyword reads data from main memory than cache and when it releases the lock.
  • 또한 주 메모리에서 쓰기 작업을 플러시하여 메모리 불일치 오류를 제거합니다.

단점 Synchronization Mechanism

Synchronization Mechanisms have poor performance.

예를 들어

  • A1, A2, A3, A4, A5라는 XNUMX개의 프로세스가 있다고 가정합니다.
  • 그들은 공유 리소스가 한 번에 하나의 스레드에 액세스하기를 기다리고 있습니다.
  • 모든 프로세스는 계속 대기하므로 대기열의 마지막 프로세스는 다른 모든 프로세스가 완료될 때까지 기다려야 합니다.

요약

  • Synchronization refers to the ability to control the access of multiple threads to any shared resource.
  • Java has two types of synchronization methods: 1) 방법 synchronization and 2) Thread sync정시화.
  • Java의 잠금은 모니터 또는 잠금으로 알려진 내부 엔터티를 중심으로 구축됩니다.
  • A Multithreaded program is a method or block protected from interference from other threads sharing the same resource indicated using the `synchronized` keyword.
  • Any method that is declared as synchronized is known as a synchronized method.
  • 자바에서는 synchronized method locks are accessed on the method, whereas synchronized block locks are accessed on the object.
  • 정적에서 synchronization, lock access is on the class, not the object and method.
  • 의 주요 목적은 synchronization in Java is to prevent inconsistent data by preventing thread interference.
  • 이 방법의 가장 큰 단점은 모든 프로세스가 대기 상태로 유지되므로 대기열의 마지막 프로세스가 다른 모든 프로세스가 완료될 때까지 기다려야 한다는 것입니다.