>  기사  >  Java  >  Java 스레드에서 객체의 동기화 및 비동기성에 대한 분석 예

Java 스레드에서 객체의 동기화 및 비동기성에 대한 분석 예

黄舟
黄舟원래의
2017-07-20 14:16:021975검색

아래 편집기에서는 Java 스레드 객체의 동기화 및 비동기성에 대한 기사를 제공합니다(예제 설명). 편집자님이 꽤 좋다고 생각하셔서 지금 공유하고 모두에게 참고용으로 드리고자 합니다. 에디터를 따라가며 함께 살펴볼까요

1. 멀티 스레드 환경의 동기화와 비동기

동기화:A 스레드가 리소스를 요청하려고 하는데 이 리소스를 B가 사용하고 있습니다. 동기화 메커니즘이 존재하고 스레드 A가 이를 요청할 수 없기 때문에 스레드 A는 대기만 할 수 있습니다.


package com.jalja.org.thread.demo01;

public class Thread02 {
 public synchronized void method1(){
  System.out.println("method1:"+Thread.currentThread().getName());
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 public synchronized void method2(){
  System.out.println("method2:"+Thread.currentThread().getName());
 }
 public static void main(String[] args) {
  final Thread02 th=new Thread02();
  Thread thread1=new Thread(new Runnable() {
   public void run() {
    th.method1();
   }
  },"th1");
  
  Thread thread2=new Thread(new Runnable() {
   public void run() {
    th.method2();
   }
  },"th2");
  
  thread1.start();
  thread2.start();
 }
}

출력을 관찰하세요. method1:th1은 3초 후에 method2:th2를 출력합니다. 이는 method2()와 method1()이 모두 동기 메서드이고 스레드 thread1과 thread2가 동일한 개체에서 작동하기 때문입니다. thread2가 method2() 메서드를 실행할 때 먼저 번째 객체의 잠금을 획득해야 합니다.

비동기: 스레드 A가 리소스를 요청하려고 하지만 이 리소스는 스레드 B에서 사용 중입니다. 동기화 메커니즘이 없기 때문에 스레드 A는 계속 요청할 수 있으며 스레드 A는 기다릴 필요가 없습니다.


package com.jalja.org.thread.demo01;

public class Thread02 {
 public synchronized void method1(){
  System.out.println("method1:"+Thread.currentThread().getName());
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 public void method2(){
  System.out.println("method2:"+Thread.currentThread().getName());
 }
 public static void main(String[] args) {
  final Thread02 th=new Thread02();
  Thread thread1=new Thread(new Runnable() {
   public void run() {
    th.method1();
   }
  },"th1");
  
  Thread thread2=new Thread(new Runnable() {
   public void run() {
    th.method2();
   }
  },"th2");
  
  thread1.start();
  thread2.start();
 }
}

출력을 관찰하세요. method1:th1과 method2:th2가 동시에 출력됩니다. 이는 method2가 동기화 제어를 추가하지 않으므로 스레드 thread2는 실행 시 실행 권한(객체 잠금)을 얻을 필요가 없기 때문입니다. method2() 메서드.

2. 데이터의 더러운 읽기

비즈니스를 설계할 때 비즈니스의 무결성을 고려해야 합니다. 그렇지 않으면 데이터 일관성 문제가 발생합니다.


package com.jalja.org.thread.demo01;

public class Thread03 {
 private String name="zs";
 private String passWorrd="123";
 public synchronized void setValue(String name,String passWord){
  this.name=name;
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  this.passWorrd=passWord;
  System.out.println("set:name="+this.name +" passWorrd="+this.passWorrd);
 }
 public void getValue(){
  System.out.println("get:name="+this.name +" passWorrd="+this.passWorrd);
 }
 public static void main(String[] args) throws InterruptedException {
  final Thread03 th=new Thread03();
  Thread thread=new Thread(new Runnable() {
   public void run() {
    th.setValue("LS", "456");
   }
  });
  thread.start();
  Thread.sleep(100);
  th.getValue();
 }
}

결과: get:name=LS passWorrd=123 set:name=LS passWorrd=456 결과를 보면 분명히 데이터 가져오기에 문제가 있음을 알 수 있습니다. 스레드 스레드가 설정 중이고, 메인 스레드가 get 메소드를 실행 중입니다. 이러한 상황을 방지하려면 스레드가 동일한 개체의 데이터를 작업할 때, 그렇지 않으면 다른 스레드도 동시에 개체의 데이터를 작업하게 되는지 확인해야 합니다. 이 경우 get 메소드에 동기화 키워드를 추가할 수 있습니다.

위 내용은 Java 스레드에서 객체의 동기화 및 비동기성에 대한 분석 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.