1 / 20

12. 프로세스와 쓰레드

12. 프로세스와 쓰레드. 최종명 choijm@dreamwiz.com. 12.1 프로세스. 프로그램 명령어들의 연속 일반적으로 하드디스크에 저장됨 프로세스 실행중인 프로그램 하드디스크에서 메모리로 로드되어 실행중임 멀티프로세싱 여러 개의 프로세스가 한 개의 CPU 에서 동시에 실행됨 프로세스 생성과 실행. 12.1 프로세스. 예제 : Browser.java. 5 try { 6 String param = "";

macon
Download Presentation

12. 프로세스와 쓰레드

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 12. 프로세스와 쓰레드 최종명 choijm@dreamwiz.com

  2. 12.1 프로세스 • 프로그램 • 명령어들의 연속 • 일반적으로 하드디스크에 저장됨 • 프로세스 • 실행중인 프로그램 • 하드디스크에서 메모리로 로드되어 실행중임 • 멀티프로세싱 • 여러 개의 프로세스가 한 개의 CPU에서 동시에 실행됨 • 프로세스 생성과 실행

  3. 12.1 프로세스 • 예제: Browser.java 5 try { 6 String param = ""; 7 if(args.length > 0) { 8 param = args[0]; 9 } 10 Process proc = Runtime.getRuntime().exec( 11 "C:/Program Files/Internet Explorer/IEXPLORE " + param); 12 } catch(IOException e) { …

  4. 12.2 쓰레드 기초 • 쓰레드 • 실행될 명령어들의 연속 • 멀티쓰레드 프로그램 • 한 프로세스에서 동시에 실행되는 쓰레드가 여러 개 존재 • C/C++ 언어에서 쓰레드 프로그래밍 • POSIX Thread API 함수를 이용해서 작성 • 자바에서 쓰레드 프로그래밍 • Thread 클래스 상속 • run() 메소드 재정의 • Runnable 인터페이스 구현 • run() 메소드 구현

  5. 12.2 쓰레드 기초 • 예제: Worker.java 1 public class Worker extends Thread { 2 protected String job; 3 4 public Worker(String name, String job) { 5 super(name); 6 this.job = job; 7 } 8 9 public void run() { 10 System.out.println(getName() + "는 " + job + 11 "를 열심히 합니다"); 12 }

  6. 12.2 쓰레드 기초 • 예제: MyHome.java 3 protected Worker ma, dol; … 7 ma = new Worker("마당쇠", "마당쓸기"); 8 dol = new Worker("돌쇠", "장작패기"); … 11 public void let() { 12 System.out.print("안녕하세요. "); 13 System.out.println("저는 주인입니다."); 14 ma.start(); 15 dol.start(); … 19 MyHome home = new MyHome(); 20 home.let();

  7. 12.2 쓰레드 기초 • 예제: TCarFactory.java 1 public class TCarFactory implements Runnable { 2 protected Thread engineMaker, frameMaker; 3 protected int engineCount, frameCount; 4 protected int carCount; 5 protected boolean engineMakerStop; 6 protected boolean frameMakerStop; 7 8 public TCarFactory(int c) { 9 carCount = c; 10 engineMaker = new Thread(this, "엔진"); 11 frameMaker = new Thread(this, "프레임"); 12 engineMakerStop = false; 13 frameMakerStop = false;

  8. 12.2 쓰레드 기초 • 예제: TCarFactory.java(계속) 16 public void operate() { 17 engineMaker.start(); 18 frameMaker.start(); 19 int k = 0; 20 while(k < carCount) { 21 if(engineCount > 0 && frameCount > 0) { 22 k++; 23 engineCount--; 24 frameCount--; 25 System.out.println(k + "번째 자동차를 생산합니다."); 26 } 27 int count = (int)(Math.random() * Integer.MAX_VALUE); 28 for(int i =0; i < count; i++) { 29 // 자동차를 조립하는 작업

  9. 12.2 쓰레드 기초 • 예제: TCarFactory.java(계속) 39 public void run() { 40 String name = Thread.currentThread().getName(); 41 int totalEngine = 0; 42 int totalFrame = 0; 43 if(name.equals("엔진")) { 44 while(engineMakerStop == false && totalEngine < carCount) { 45 int count = (int)(Math.random() * Integer.MAX_VALUE); 46 for(int i =0; i < count; i++) { 47 // 엔진을 만드는 작업 48 } 49 totalEngine++; 50 engineCount++; 51 System.out.println("엔진을 하나 만들었습니다.");

  10. 12.2 쓰레드 기초 • 쓰레드 종료 while(stop == false) { ... } while(true) { ... if(test) break; }

  11. 12.2 쓰레드 기초 • 예제: PriorityTest.java 13 Thread.currentThread().setPriority(Thread.MAX_PRIORITY); 14 ma.start(); 15 dol.start(); 16 ddeg.start(); 17 try { 18 System.out.println("마당쇠 우선순위를 +2 증가"); 19 ma.setPriority(ma.getPriority() + 2); 20 Thread.sleep(3000); 21 System.out.println("돌쇠 우선순위를 +4 증가"); 22 dol.setPriority(dol.getPriority() + 4); 23 Thread.sleep(5000); 24 } catch(InterruptedException e) { } 25 stop = true;

  12. 12.2 쓰레드 기초 • 예제: LockTest.java 23 public synchronized void doCriticalJob() { 24 String name = Thread.currentThread().getName(); 25 System.out.print("[" + name + "\t"); 26 try { 27 int time = (int)(Math.random() * 2000); 28 Thread.sleep(time); 29 } catch(Exception e) { } 30 System.out.println("\t" + name + "]"); 31 }

  13. 12.3 쉘 만들기 • 예제: Shell.java 15 public void run() { 16 try { 17 Process proc = rt.exec(cmd); 18 InputStream in = proc.getInputStream(); 19 byte buffer[] = new byte[1024]; 20 int n = -1; 21 while ((n = in.read(buffer)) != -1) { 22 System.out.print(new String(buffer, 0, n)); 23 } 24 } catch(Exception e) { 25 System.out.println(cmd + 26 " 명령어를 실행시킬 수 없습니다.");

  14. 12.3 쉘 만들기 • 예제: Shell.java(계속) 30 public void execute() { 31 while(true) { 32 try { 33 System.out.print("$"); 34 cmd = reader.readString(); 35 Process proc = null; 36 if(cmd.equals("exit")) 37 break; 38 if(cmd.equals("dir")) { 39 proc = rt.exec("cmd /c dir "); 40 } else if(cmd.startsWith("go ")) { 41 cmd = cmd.substring(3); 42 Thread th = new Thread(this); 43 th.start();

  15. 12.3 쉘 만들기 • 예제: Shell.java(계속) 47 } else { 48 proc = rt.exec(cmd); 49 } 50 InputStream in = proc.getInputStream(); 51 byte buffer[] = new byte[1024]; 52 int n = -1; 53 while ((n = in.read(buffer)) != -1) { 54 System.out.print(new String(buffer, 0, n)); 55 } 56 } catch(Exception e) { 57 e.printStackTrace(); 58 }

  16. 12.4 생산자와 소비자 • 생산자와 소비자 • 여러 개의 프로세스 혹은 쓰레드들이 서로 협력해서 어떤 특정 작업을 수행함 • 생산자 – 창고(Monitor)가 꽉찬 경우에는 소비자가 물건을 가져갈 때까지 기다려야 한다. • 소비자 – 창고가 빈 경우에는 생산자가 물건을 만들 때까지 기다려야 한다.

  17. 12.4 생산자와 소비자 • 예제: Producer.java 10 public void run() { 11 char c; 12 for (int i = 0; i < 20; i++) { 13 c = alphabet.charAt((int)(Math.random() * 25)); 14 monitor.add(c); 15 System.out.println("ADD --> " + c); 16 try { 17 sleep((int)(Math.random() * sleepTime)); 18 sleepTime = (int)(Math.random() * 1000); 19 } catch (InterruptedException e) { } 20 }

  18. 12.4 생산자와 소비자 • 예제: Consumer.java 9 public void run() { 10 char c; 11 for (int i = 0; i < 20; i++) { 12 c = monitor.eat(); 13 System.out.println("REMOVE <-- " + c); 14 try { 15 sleep((int)(Math.random() * sleepTime)); 16 sleepTime = (int)(Math.random() * 1000); 17 } catch (InterruptedException e) { } 18 }

  19. 12.4 생산자와 소비자 • 예제: Monitor.java 8 public synchronized char eat() { 9 char toReturn; 10 while (isEmpty == true) { 11 try { 12 System.out.println("\t\tBuffer is empty."); 13 wait(); 14 } catch (InterruptedException e) { } … 18 if (eatnext == addnext ) { 19 isEmpty = true; 20 } 21 isFull=false; 22 notify(); 23 return(toReturn);

  20. 12.4 생산자와 소비자 • 예제: Monitor.java(계속) 26 public synchronized void add(char c) { 27 while (isFull == true) { 28 try { 29 System.out.println("\t\tBuffer is full."); 30 wait(); 31 } catch (InterruptedException e) { } 32 } 33 buffer[addnext] = c; 34 addnext = (addnext + 1) % 6; 35 if (addnext == eatnext) { 36 isFull = true; 37 } 38 isEmpty = false; 39 notify();

More Related