언어/Java

Java(자바) - 멀티쓰레드(Multi Thread) 동기화 간단 쉬운 예제

[좋은사람] 2017. 9. 11. 20:39

Java(자바) - 멀티 쓰레드(Multi Thread) 동기화 예제

 

(1). 개요

Java 에서 보통 싱글 쓰레드(Single Thread) 인 경우는 프로세스 내에서 단 한 개의 쓰레드가 실행된다.

 멀티 쓰레드(Multi Thread) 환경은 각 프로세스 내에서 자원을 공유한다.

③ 즉, 멀티 쓰레드(Multi Thread) 환경에서는 원래 의도와는 다른 예측 범위 밖의 실행 결과가 도출 될 수 있다.

 이처럼 멀티 쓰레드(Multi Thread) 환경에서 동기화는 중요한 문제이다. 아래 간단한 예제를 통해서 결과를 예측해보자.

 

 

(2). Multithreading Example without Synchronization (동기화 없는 멀티 쓰레드 예제)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//WithoutSynchronization.java
 
class PrintDemo {
   public void printCount() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Counter   ---   "  + i );
         }
      }catch (Exception e) {
         System.out.println("Thread  interrupted.");
      }
   }
}
 
class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   PrintDemo  PD;
 
   ThreadDemo( String name,  PrintDemo pd) {
      threadName = name;
      PD = pd;
   }
   
   public void run() {
      PD.printCount();
      System.out.println("Thread " +  threadName + " exiting.");
   }
 
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}
 
public class TestThread {
   public static void main(String args[]) {
 
      PrintDemo PD = new PrintDemo();
 
      ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
      ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
 
      T1.start();
      T2.start();
 
         // 쓰레드 종료 대기
         try {
         T1.join();
         T2.join();
      }catch( Exception e) {
         System.out.println("Interrupted");
      }
   }
}
 
 
//OUTPUT(결과)
 
Starting Thread - 1
Starting Thread - 2
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   5
Counter   ---   2
Counter   ---   1
Counter   ---   4
Thread Thread - 1  종료.
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 2  종료.
 
 
 
 
cs

 

  synchronized 키워드를 통해 공유 자원 데이터에 Lock을 걸고 쓰레드의 실행 순서를 제어한다.


(3). Multithreading Example with Synchronization (동기화 있는 멀티 쓰레드 예제)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//WithSynchronization.java
 
class PrintDemo {
   public void printCount() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Counter   ---   "  + i );
         }
      }catch (Exception e) {
         System.out.println("Thread  interrupted.");
      }
   }
}
 
class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   PrintDemo  PD;
 
   ThreadDemo( String name,  PrintDemo pd) {
      threadName = name;
      PD = pd;
   }
   
   public void run() {
      synchronized(PD) {
         PD.printCount();
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
 
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}
 
public class TestThread {
 
   public static void main(String args[]) {
      PrintDemo PD = new PrintDemo();
 
      ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
      ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );
 
      T1.start();
      T2.start();
 
      // 쓰레드 종료 대기
      try {
         T1.join();
         T2.join();
      }catch( Exception e) {
         System.out.println("Interrupted");
      }
   }
}
 
 
//OUTPUT(결과)
 
Starting Thread - 1
Starting Thread - 2
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 1  종료.
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 2  종료.
 
 
 
cs