>  기사  >  Java  >  동시 출력을 달성하기 위한 Java 멀티스레딩

동시 출력을 달성하기 위한 Java 멀티스레딩

高洛峰
高洛峰원래의
2017-01-05 16:58:341722검색

고전적인 인터뷰 질문: 두 개의 스레드가 각각 AB를 인쇄합니다. 여기서 스레드 A는 A를 인쇄하고 스레드 B는 B를 인쇄합니다. 각각은 ABABABABA로 나타나도록 10번 인쇄합니다. 효과

package com.shangshe.path;
 
public class ThreadAB {
 
  /**
  * @param args
  */
  public static void main(String[] args) {
     
    final Print business = new Print();
     
    new Thread(new Runnable() {
      public void run() {
        for(int i=0;i<10;i++) {
          business.print_A();
        }
      }
    }).start();
     
    new Thread(new Runnable() {
      public void run() {
        for(int i=0;i<10;i++) {
          business.print_B();
        }
      }
    }).start();
     
  }
}
class Print {
   
  private boolean flag = true;
   
  public synchronized void print_A () {
    while(!flag) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.print("A");
    flag = false;
    this.notify();
  }
   
  public synchronized void print_B () {
    while(flag) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.print("B");
    flag = true;
    this.notify();
  }
}

위의 예에서 , 3개의 스레드 또는 심지어 n개의 스레드로 프로그램을 설계할 수 있습니다. 아래의 예는 3개의 스레드로 A, B, C를 각각 10번 인쇄하므로 ABCABC..의 효과가 나타납니다.

public class ThreadABC {
 
  /**
   * @param args
   */
  public static void main(String[] args) {
     
    final Print business = new Print();
     
    new Thread(new Runnable() {
      public void run() {
        for(int i=0;i<100;i++) {
          business.print_A();
        }
      }
    }).start();
     
    new Thread(new Runnable() {
      public void run() {
        for(int i=0;i<100;i++) {
          business.print_B();
        }
      }
    }).start();
     
    new Thread(new Runnable() {
      public void run() {
        for(int i=0;i<100;i++) {
          business.print_C();
        }
      }
    }).start();
     
  }
}
class Print {
   
  private boolean should_a = true;
  private boolean should_b = false;
  private boolean should_c = false;
   
  public synchronized void print_A () {
    while(should_b || should_c) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.print("A");
    should_a = false;
    should_b = true;
    should_c = false;
    this.notifyAll();
  }
   
  public synchronized void print_B () {
    while(should_a || should_c) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.print("B");
    should_a = false;
    should_b = false;
    should_c = true;
    this.notifyAll();
  }
   
  public synchronized void print_C () {
    while(should_a || should_b) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    System.out.print("C");
    should_a = true;
    should_b = false;
    should_c = false;
    this.notifyAll();
  }
}

소프트웨어 엔지니어링의 중요성을 다시 한번 입증합니다. 멀티 스레드 프로그램에서는 비즈니스 로직 코드를 동일한 클래스에 넣어 응집력을 높이고 결합도를 낮추어야 합니다


더 많은 Java 멀티스레딩 구현 및 동시 출력 관련 글은 PHP 중국어 홈페이지를 주목해주세요!


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