과제개요 Nachos Project Assignment #2 스레드와동기화 이번과제는 Nachos 운영체제의스레드와동기화부분의코드와기능을분석하고여러가지기능을구현함으로써운영체제의스레드와동기화를파악할수있는과제입니다. 운영체제의핵심적인기능인스레드와동기화를파악하면서시스템에치명

Size: px
Start display at page:

Download "과제개요 Nachos Project Assignment #2 스레드와동기화 이번과제는 Nachos 운영체제의스레드와동기화부분의코드와기능을분석하고여러가지기능을구현함으로써운영체제의스레드와동기화를파악할수있는과제입니다. 운영체제의핵심적인기능인스레드와동기화를파악하면서시스템에치명"

Transcription

1 운영체제 2 차 Nachos Project 팀명 구성원 garbage 2000XXXX X X X 2000XXXX X X X 2000XXXX X X X 과목명 : 운영체제 교수님 : XXX 교수님 제출일 : 0X 년 X 월 X 일 ( 火 )

2 과제개요 Nachos Project Assignment #2 스레드와동기화 이번과제는 Nachos 운영체제의스레드와동기화부분의코드와기능을분석하고여러가지기능을구현함으로써운영체제의스레드와동기화를파악할수있는과제입니다. 운영체제의핵심적인기능인스레드와동기화를파악하면서시스템에치명적인문제를일으킬수있는교착과기아상태에대한내용과예방등을학습할수있는과제인거같습니다. 팀구성원작업분담내용 저희 garbage 팀의분담내용은아래의표와같습니다. 팀명 garbage 성명학번작업내용 고 X X 김 X X 이 X X 2000XXXXX 2000XXXXX 2000XXXXX thread 코드및루틴분석 Nachos 운영체제의전체적인 System 구조분석 주석문해석 각종자료및문서검색 semaphore 코드및 condition variable 의차이점분석 동기화실험문제자료검색 Thread::Join() 구현 Nachos Java 버전에서사용된 Java 언어적특징과 C++ 버전과의차이분석 priority scheduling 구현 동기화실험식당문제구현 레포트작성 Thred 루틴분석 소스코드를분석한내용은굵은이탤릭체에그림자를넣어서 표시하였습니다. 29-1

3 KThread.java 파일소스분석 KThread.java package nachos.threads; //nachos 디렉토리안의 threads 안에포함시킴. import nachos.machine.*; //nachos 디렉토리안의 machine 디렉토리밑에있는모든함수 import 시킴. KThead * KThread 는 nachos 커널코드를실행시키기위해사용할수있는스레드로써 * 다중스레드를지원한다. * 실행하기위해새로운스레드생성할때 Runable 인터페이스로구현된클래스를 * 먼저선언해야한다. * Runable 은하나의메소드 run() 만을선언하며, 이것이바로스레드가시작되면 * 실행되는메소드이다. KThread 가생성될때 run() 메소드를통해인수를보내고 * forked 시킴. public class KThread { * Get the current thread. // current thread 얻음 the current thread. // current thread 리턴 public static KThread currentthread() { Lib.assert(currentThread!= null); return currentthread; currentthread() * currentthread 가 null 값이아니면 Lib.assert() 에 true 값전달 * true 면 assert 하고 false 면에러메시지보냄. currentthread 리턴 * * public static void assert(boolean expression) { * if (!expression) * throw new AssertionFailureError(); * public KThread() { if (currentthread!= null) { tcb = new TCB(); else { readyqueue = ThreadedKernel.scheduler.newThreadQueue(false); readyqueue.acquire(this); currentthread = this; tcb = TCB.currentTCB(); name = "main"; restorestate(); createidlethread(); 29-2

4 KThread() * 새로운 KThread 를할당한다. * 이것이첫번째 KThread 이면 idle thread 도생성한다. * currentthread 값이있으면 TCB() 생성, * currentthread 값이 null 이면 readyqueue 에 newtreadqueue 에 false 로지정. * Allocate a new KThread. 새로운 KThread 할당 * target the object whose <tt>run</tt> method is called. * run() 메소드에있는 target 호출 public KThread(Runnable target) { this(); this.target = target; KThread(Runnable target) * Runnable 의 target( 실행될스레드 ) 을인수로받아 KThread 의 target 에저장. * Set the target of this thread. 이스레드에서 target 을정함 * target the object whose <tt>run</tt> method is called. * target 은 run() 메소드에서호출된객체이다 this thread. 이스레드를리턴함 public KThread settarget(runnable target) { Lib.assert(status == statusnew); this.target = target; return this; * Set the name of this thread. This name is used for debugging purposes * only. * 이스레드의이름을정한다. 이것의이름은단지디버깅을하기위해서사용한다. * name the name to give to this thread. * 이스레드의이름을얻음 this thread. 이것의스레드리턴한다 public KThread setname(string name) { this.name = name; return this; 29-3

5 * Get the name of this thread. This name is used for debugging purposes * only. * 이것의스레드의이름을얻는다. * 이것의이름은단지디버깅을하기위해서만사용된다. * the name given to this thread. * 이것의스레드에서주어진이름을리턴함 public String getname() { return name; * Get the full name of this thread. This includes its name along with its * numerical ID. This name is used for debugging purposes only. * 이것의전체이름을얻는다. 이것은숫자로된 ID 를포함한다. * 이이름도단지디버깅을위해서만사용된다. * the full name given to this thread. * 이스레드에서얻어진전체이름을반환한다. public String tostring() { return (name + " (#" + id + ")"); * Deterministically and consistently compare this thread to another * thread. * 다른스레드에대해이스레드를비교한다. public int compareto(object o) { KThread thread = (KThread) o; if (id < thread.id) return -1; else if (id > thread.id) return 1; else return 0; 이객체 o 를인수로받아들임. 현재 id 값이더작으면 -1 을반환하고현재 id 값이더크면 1 을반환현재 id 와다른스레드의 id 가같으면 0 을반환한다. 29-4

6 * 이스레드를실행시키기위해 fork() 메소드호출. * 이결과는 2 개의스레드가병행적으로실행되도록한다. * 이 2 개의스레드는 fork() 메소드로부터호출되어반환된 current thread 와 * run() 메소드에의해 target 되어실행되는또다른스레드이다. public void fork() { Lib.assert(status == statusnew); Lib.assert(target!= null); Lib.debug(dbgThread, "Forking thread: " + tostring() + " Runnable: " + target); // 이 forking 될스레드의이름과 runnable 된 target 을저장 boolean intstatus = Machine.interrupt().disable(); // 초기상태를 false 로지정함 tcb.start(new Runnable() { public void run() { runthread(); ); // tcb 안에있는스레드를실행시키기위해 start() 를호출함 // Runnable() 의공간을할당시키고 run() 을통해서실행될수있다. ready(); // ready() 함수호출 : 스레드를실행하기위해준비시킴 Machine.interrupt().restore(intStatus); // intstatus 를복구시킴 private void runthread() { begin(); target.run(); finish(); // run//thread() 는 private 로선언 ( 현재클래스에서만사용가능 ) private void begin() { Lib.debug(dbgThread, "Beginning thread: " + tostring()); // flag 상태디버깅 Lib.assert(this == currentthread); restorestate(); Machine.interrupt().enable(); // 인터럽트가능하게함 29-5

7 * finish() 는 current thread 가끝나고 * 안전하게스레드가제거되기위해 schedule 한다. * 이메소드는스레드의 run() 값이반환될때자동으로호출된다. * 그러나또한직접호출될수있다. * * current thread 의스택과다른실행상태가여전히사용중일수있기때문에 * current thread 는즉시제거될수없다. * * 대신이스레드는다음레드가실행됨에따라자동으로제거되고 * 안전하게삭제된다. public static void finish() { Lib.debug(dbgThread, "Finishing thread: " + currentthread.tostring()); Machine.interrupt().disable(); Machine.autoGrader().finishingCurrentThread(); Lib.assert(toBeDestroyed == null); tobedestroyed = currentthread; currentthread.status = statusfinished; //currentthread 의상태를 finish 상태로바꿔줌 sleep(); // sleep() 함수호출. * 다른스레드가실행하기위해 ready 상태에있으면 * 그스레드에게 CPU 를양도한다. * 만약레디큐에현재스레드를놓으면언젠가는다시스케줄되어야한다. * * 만약다른스레드가실행할준비가되어있지않다면즉시리턴한다. * 그렇지않으면 readyqueue.nextthread() 에의해다시선택되어진 * current thread 를리턴한다. * * 인터럽트는 disable 된다. * current thread 는스스로 ready queue 에더해지고다음 thread 와교환한다. * return 될때인터럽트는그전상태로복구된다. * cyield() 는인터럽트가 disabled 된상태로호출된다. public static void yield() { Lib.debug(dbgThread, "Yielding thread: " + currentthread.tostring()); Lib.assert(currentThread.status == statusrunning); boolean intstatus = Machine.interrupt().disable(); currentthread.ready(); runnextthread(); Machine.interrupt().restore(intStatus); //currentthread 는 ready() 함수호출 // 인터럽트그전상태로복구 29-6

8 * current thread 가끝나거나 block 되었을때 CPU 를양도한다. * 이스레드는반드시 current thread 이어야만한다. * * current thread 가 ( 동기화인세마포어, 락, 컨디션에의해 ) 블록되었다면 * 언젠가는어떤스레드는이스레드를재시작시킬것이고, * 새로스케줄될수있으므로레디큐위에다시놓여진다. * 그렇지않으면 finish() 메소드는다음스레드의실행에의해 * 이스레드가제거되되도록스케줄되어야한다. public static void sleep() { Lib.debug(dbgThread, "Sleeping thread: " + currentthread.tostring()); if (currentthread.status!= statusfinished) currentthread.status = statusblocked; // currentthread 상태가 finish 가아니면 currentthread 상태를 block 으로저장한다. runnextthread(); // 다음스레드를실행한다. * 이스레드를레디상태로이동하고레디큐의스케줄러에추가한다. public void ready() { Lib.debug(dbgThread, "Ready thread: " + tostring()); Lib.assert(status!= statusready); status = statusready; // 상태를레디상태로저장 if (this!= idlethread) readyqueue.waitforaccess(this); Machine.autoGrader().readyThread(this); * 이스레드가끝나기를기다린다. * 만약이스레드가이미끝났다면즉시리턴한다. * join() 메소드는단지한번만호출되어야만한다. * 이스레드는 current thread 가되서는안된다. 29-7

9 public void join() { Lib.debug(dbgThread, "Joining to thread: " + tostring()); Lib.assert(this!= currentthread); * idle 스레드생성. * 실행하기위해준비된스레드가없을때에는 runnextthread() 를호출되고 * 그것은 idle thread 를실행시킬것이다. * idle 스레드는절대 block 되지않고 * 단지모든다른스레드들이블록되었을때만할당된다. private static void createidlethread() { Lib.assert(idleThread == null); idlethread = new KThread(new Runnable() { public void run() { while (true) yield(); ); idlethread.setname("idle"); Machine.autoGrader().setIdleThread(idleThread); idlethread.fork(); * 다음실행될스레드를결정한다. * 그다음 run() 을이용하여 CPU 을 dispatch 시킨다. private static void runnextthread() { KThread nextthread = readyqueue.nextthread(); if (nextthread == null) nextthread = idlethread; // 다음실행될스레드가없으면다음스레드를 idle 스레드로바꾼다. nextthread.run(); * 이스레드에 CPU 를 dispatch 시킨다. * current thread 의상태를저장하고 TCB.contextSwitch() 의호출에의해 * 새로운스레드로바꾼다. * 그리고새로운스레드의상태를 load 시킨다. * 새로운스레드는 current thread 가된다. * * 만약새로운스레드와그전스레드가같으면이메소드는 * savestate(), contextswitch(), restorestate() 를호출해야한다. 29-8

10 private void run() { Machine.yield(); currentthread.savestate(); Lib.debug(dbgThread, "Switching from: " + currentthread.tostring() + " to: " + tostring()); currentthread = this; tcb.contextswitch(); currentthread.restorestate(); * 만실행이되기위해이스레드를준비한다. * statusrunning 을위한 status 를정하고 tobedestroyed 를체크한다. protected void restorestate() { Lib.debug(dbgThread, "Running thread: " + currentthread.tostring()); Lib.assert(this == currentthread); Lib.assert(tcb == TCB.currentTCB()); Machine.autoGrader().runningThread(this); status = statusrunning; if (tobedestroyed!= null) { tobedestroyed.tcb.destroy(); tobedestroyed.tcb = null; tobedestroyed = null; /* * 스레드를프로세서와끊기위한준비. * 커널스레드는여기서아무것도필요하지않다. protected void savestate() { Lib.assert(this == currentthread); private static class PingTest implements Runnable { PingTest(int which) { this.which = which; 29-9

11 public void run() { for (int i=0; i<5; i++) { System.out.println("*** thread " + which + " looped " + i + " times"); currentthread.yield(); private int which; public static void selftest() { Lib.debug(dbgThread, "Enter KThread.selfTest"); new KThread(new PingTest(1)).setName("forked thread").fork(); new PingTest(0).run(); private static final char dbgthread = 't'; * Additional state used by schedulers. * 스케줄러에의해사용되는추가적인상태. * nachos.threads.priorityscheduler.threadstate public Object schedulingstate = null; private static final int statusnew = 0; private static final int statusready = 1; private static final int statusrunning = 2; private static final int statusblocked = 3; private static final int statusfinished = 4; // 스레드 5 가지상태정의 * 이스레드의상태. * 스레드는 new, ready, running, blocked 의상태로이루어질수있다. private int status = statusnew; private String name = "(unnamed thread)"; private Runnable target; private TCB tcb; * 이스레드를위한식별자는유일하다. * 이식별자는스레드를비교하고결정하는데사용한다

12 private int id = numcreated++; Number of times the KThread constructor was called. private static int numcreated = 0; private static ThreadQueue readyqueue = null; private static KThread currentthread = null; private static KThread tobedestroyed = null; private static KThread idlethread = null; Thread 생성에서소멸까지의경로 Nachos Java 버전쓰레드의생성에서소멸까지의도식 KThread.KThread (Garbage collection) New KThread.fork KThread.run (TCB.contextSwitch) Finished KThread.finish Ready Running KThread.ready KThread.yield Blocked KThread.sleep 1 먼저스레드가생성된다. KThread.KThread 에의해스레드생성 public KThread() { if (currentthread!= null) { tcb = new TCB(); else { readyqueue = ThreadedKernel.scheduler.newThreadQueue(false); readyqueue.acquire(this); currentthread = this; tcb = TCB.currentTCB(); name = "main"; restorestate(); 29-11

13 createidlethread(); public KThread(Runnable target) { this(); this.target = target; createidlethread(); 2 생성된스레드를 Ready 시킨다. public void fork() { Lib.assert(status == statusnew); Lib.assert(target!= null); KThread.fork 에의해 Ready 시킴 Lib.debug(dbgThread, "Forking thread: " + tostring() + " Runnable: " + target); boolean intstatus = Machine.interrupt().disable(); tcb.start(new Runnable() { public void run() { runthread(); ); ready(); Machine.interrupt().restore(intStatus); 3 스레드를실행시킨다. KThread.run 에의해 Thread 실행시킴 private void run() { Machine.yield(); currentthread.savestate(); Lib.debug(dbgThread, "Switching from: " + currentthread.tostring() + " to: " + tostring()); currentthread = this; tcb.contextswitch(); currentthread.restorestate(); // 문맥교환일어남 29-12

14 4 yield() 가호출되어 Running 상태에서 Ready 상태로전환된다. KThread.yield 에의해 Running 상태에서 Ready 상태로전이됨. public static void yield() { Lib.debug(dbgThread, "Yielding thread: " + currentthread.tostring()); Lib.assert(currentThread.status == statusrunning); boolean intstatus = Machine.interrupt().disable(); currentthread.ready(); runnextthread(); Machine.interrupt().restore(intStatus); 5 sleep() 메서드에의해 block 된다. KThread.sleep 에의해 block 상태로바뀜 public static void sleep() { Lib.debug(dbgThread, "Sleeping thread: " + currentthread.tostring()); if (currentthread.status!= statusfinished) currentthread.status = statusblocked; runnextthread(); 6 ready() 메서드에의해다시 Ready 상태로돌아온다. KThread.ready 에의해다시 ready 상태로변함 public void ready() { Lib.debug(dbgThread, "Ready thread: " + tostring()); Lib.assert(status!= statusready); status = statusready; if (this!= idlethread) readyqueue.waitforaccess(this); Machine.autoGrader().readyThread(this); 29-13

15 7 finish() 메서드에의해스레드가소멸된다. KThread.finish 에의해스레드소멸 public static void finish() { Lib.debug(dbgThread, "Finishing thread: " + currentthread.tostring()); Machine.interrupt().disable(); Machine.autoGrader().finishingCurrentThread(); Lib.assert(toBeDestroyed == null); tobedestroyed = currentthread; currentthread.status = statusfinished; sleep(); contextswitch() 분석 위에있는 thread 생성에서소멸까지의경로에서볼수있듯이 run() 메소드에서문맥교환이일어난다. TCB(Thread Control Block) 에순서대로저장되어있는 Thread가 Ready 상태에서 Running 상태로되면서스레드를문맥교환해준다. private void run() {... currentthread = this; tcb.contextswitch(); => 문맥교환일어남 currentthread.restorestate(); 왜 sleep() 은 interrupt disable을가정했을까? sleep() 은스레드가잠시 block 되도록만드는데 block 된상태에서 interrupt가되면 block이해재되고문제가발생하기때문에 interrupt().disabled() 로설정한다

16 Semaphore.java 파일소스분석 package nachos.threads; import nachos.machine.*; semaphore.java * A <tt>semaphore</tt> is a synchronization primitive with an unsigned value. * A semaphore has only two operations: * 세마포어는 unsigned 값을가진동기화도구이다. 세마포어는 2 개의연산만가진다. * <ul> * <li><tt>p()</tt>: waits until the semaphore's value is greater than zero, * then decrements it. * <li><tt>v()</tt>: increments the semaphore's value, and wakes up one thread * waiting in <tt>p()</tt> if possible. * </ul> * P(): 세마포어의값을하나감소시킨다음그값이 0 보다커질때까지기다린다. * V(): 세마포어의값을하나증가시키고 P() 안에기다리고있는한스레드의실행을재시작시킨다. public class Semaphore { public Semaphore(int initialvalue) { value = initialvalue; // 초기값설정 * Atomically wait for this semaphore to become non-zero and decrement it. *public Semaphore( int initialvalue); Semaphore class 의 2-parameter constructor 이다. 첫번째 parameter debugname 은 debug 용 semaphore 의 name 이고, initialvalue 는 semaphore 의초기 value 값이다. 이 value 는 P() 에서감소하고, V() 에서증가하는값이다. 이값을 1 로하면, 한 critical section 에한 thread 만들어갈수있음을의미한다. 내부에서는 queue 라는 List 변수를만들어다른 thread 가 critical section 으로들어갔을때 P() 를부르게되면기다리게되는 thread 들을저장하는 FIFO 형태의 queue list 이다. public void P() { boolean intstatus = Machine.interrupt().disable(); if (value == 0) { waitqueue.waitforaccess(kthread.currentthread()); KThread.sleep(); else { value--; 29-15

17 Machine.interrupt().restore(intStatus); void P() atomic 하게구현된세마포어함수이다. thread 가진입할때마다 value 를감소시키고, value 가 0 이라면더 thread 가진입할수없는상황이다. 이때 thread 가진입을시도하면 Sleep() 당해서 queue 에달리게된다. * Atomically increment this semaphore and wake up at most one other thread * sleeping on this semaphore. -> 세마포어를증가시키고 sleeping 되어있는다른스레드중하나을재시작시킨다. public void V() { boolean intstatus = Machine.interrupt().disable(); KThread thread = waitqueue.nextthread(); if (thread!= null) { thread.ready(); else { value++; Machine.interrupt().restore(intStatus); private static class PingTest implements Runnable { PingTest(Semaphore ping, Semaphore pong) { this.ping = ping; this.pong = pong; public void run() { for (int i=0; i<10; i++) { ping.p(); pong.v(); private Semaphore ping; private Semaphore pong; void V(): atomic 하게구현된세마포어함수이다. value 를하나더하고, queue 에서잠든상태로기다리고있는 thread 가있으면하나를깨워서대기중상태로만든다. * Test if this module is working. public static void selftest() { Semaphore ping = new Semaphore(0); Semaphore pong = new Semaphore(0); 29-16

18 new KThread(new PingTest(ping, pong)).setname("ping").fork(); for (int i=0; i<10; i++) { ping.v(); pong.p(); private int value; private ThreadQueue waitqueue = ThreadedKernel.scheduler.newThreadQueue(false); semaphore와 condition variable의차이점 semaphore에는 P() 함수와 V() 함수가있지만, condition variable에는 Wait() 함수와, Signal() 함수가있다. thread가 semaphore나 condition variable에서 Sleep() 하는경우, semaphore의경우, 그곳에서 thread가기다리려면 P() 함수를호출해서 semaphore.value가 0이라면 thread가그 semaphore안에있는 queue에매달리면서 Sleep() 을하고, 이미진입한 thread가계속나가면서자신의차례가올때까지 semaphore의 queue에서자고있다. 그러나 condition variable의경우에는조건없이 thread를 condition variable 안에있는 queue에매달고 Sleep() 을하는 Wait() 만이존재한다. semaphore나 condition variable에서 Sleep() 하고있는 thread를깨우기위해서 semaphore의경우에는 V() 함수를통해서그 semaphore의 queue에매달려있는 thread들을 ready-list 로넣고 semaphore 안에있는 value++ 를하지만, condition variable의경우에는 Signal() 함수를통해서 condition variable 안에있는 queue에서기다리고있는 thread들을하나깨워 ready-list로넣는다. ( 혹은 Broadcast() 를통해모두깨워서 ready 상태로만든다 ) semaphore를이용해서코딩을하는경우, 코딩을하는사람은반드시 P() 함수와 V() 함수를쌍으로구현해야한다. 만일, 이 rule을지키지않으면, 일부 thread들이 semaphore에서기다리기만하는경우가생길수있다 (dead lock). 하지만 condition variable의경우에는대체로이런위험이적다고한다

19 semaphore는 interrupt disable/enable으로 atomicity가보장된 P(), V() 함수를이용해 value값을조절하여 Synchronization을구현한다. 반면, condition variable은물론 semaphore를사용하지만이는 thread가 critical section으로진입하고나올때만호출되어지는단순한기능을한다고볼수있다. condition variable은 semaphore와다르게 critical section으로진입하지못한 thread들을저장하는자료구조 list waitqueue를사용한다. 또한 protection으로 Lock variable을사용한다. wait() 내부에서는 Release() 를부른후 P() 를불러기다린다. signal() 이불려지면, waitqueue에서나와서 V() 를호출하고 wait() 내에서 lock을 Acquire() 한다. Broadcast() 함수는 waitqueue에있는모든 thread들의 signal() 을불러준다. alarm, timer, interrupt의관계 Interrupt::OneTick() 은 stats->totalticks를증가시키고, pending interrupt가있는지없는지를검사한다 (Interrupt::CheckIfDue()). 이때 pending interrupt는 SortedList에 PendingInterrupt* 의형태로들어가게된다. 그리고, PendingInterrupt class에는 interrupt가언제처리될지와, 처리될때어떤함수를불러서처리할지에대한정보를담은 member들이들어간다. Interrupt::CheckIfDue(bool advanceclock) 에서는 PendingInterrupt 들을처리한다. 현재의 tick이인터럽트가발생해야할때의 tick보다작은경우, 인자로넘어온, advanceclock의값에따라결정된다. 만일이값이 TRUE이라면, 현재의 tick을인터럽트가발생할때만큼증가시켜주고, 인터럽트를처리한다. 예를들어 PendingInterrupt가 Timer 객체인경우를생각해보자. 우선 nachos에서는 Timer 객체는 Alarm class안에서정의된다. Alarm객체는 Kernel class에서정의된다. PendingInterrupt를처리하는경우, 그인터럽트의 CallBack() 함수를호출하게된다. 이때 Timer에대한 CallBack() 함수는 Alarm::CallBack() 함수를부른다. 이때, 이 Alarm::CallBack() 함수가, nachos 에서는 Timer인터럽트에대한 Interrupt Handler로취급된다. Interrupt Handler루틴이끝난후에, Timer::CallBack() 함수는, 다음 time interrupt를 PendingInterrupt에매단다 (Timer::SetInterrupt())

20 Thread::Join() 구현 Join() 을구현하기위해서는먼저 Join() 이무엇인지알아야하는데문제 에서 C 의 wait() 와유사한기능이라고제시하였기때문에먼저 C 의 wait() 함수가무엇인지분석하였습니다. wait() 함수는유닉스에서사용되는함수로서프로세스가대기하도록하는 함수이다. wait() 시스템콜을호출하면커널은프로세스들이종료되었는지검사하고 부모프로세스는자식프로세스가종료할때까지기다리며, 종료된자식의 PID(Process ID) 를돌려준다. 종료된프로세스를좀비 (zombie) 프로세스라고하는데, 종료된프로세스는 부모프로세스가자신에게 wait() 시스템콜을호출하기전까지좀비 프로세스로남아있는다. 만약에부모프로세스가 wait() 를호출하지않고종료된다면자식프로세스는 작업이종료된후에도 wait() 시스템콜을기다리면서좀비프로세스로남아 시스템자원을계속차지하게될것이다. 이에대한해결책으로시스템은초기화중에 init 이라는특별한시스템 프로세스를만든다. 한프로세스가종료되면커널은모든자식프로세스들의 디스크립터포인터를변경하여그들을 init 프로세스의자식으로만든다. 그리고 init 프로세스는모든자식들의실행상태를지켜보며정기적으로 wait() 시스템콜을호출하여모든좀비프로세스들을제거한다. 간단하게 C 언어로작성된소스를살펴보면서 wait() 의기능을확인해보자. 유닉스 C 언어로작성된 wait() 기능 main() { int pid; printf("parent pid of a.out: pid = fork(); // 자식프로세스생성 // 부모프로세스코드부분 if (pid > 0 ) wait((int *)0); // 자식프로세스가끝날때까지기다린다! printf("\nparent process id: %d, parent pid: exit(0); 29-19

21 // 자식프로세스코드부분 if (pid == 0) { printf("child process id: %d, parent pid: execl("/bin/ps","ps",(char *)0); fatal("execl failed"); // 에러발생 fatal("fork failed"); fatal(char *s) { perror(s); exit(1); 위의소스를보면 pid=fork(); 부분에서자식프로세스가생성되는데이는부모프로세스와똑같은코드가된다. 단, 차이점은 fork() 의값이 0이면자식프로세스이고아니면부모프로세스이다. 그래서 if (pid > 0 ) {... 이부분에서는부모프로세스만실행되고 if(pid == 0){... 부분에서는자식프로세스만실행된다. 저희조가프로젝트에사용한 Nachos Java버전에서는 threads 디렉토리아래에있는 KThread.java 파일안에 Join() 메서드가구현되어있습니다. 그리고 Java라는언어자체가 thread를구현하는데 join() 메서드를지원합니다. 따라서소스구현은위에제시한 C언어버전으로대신하고 Java언어상의 join() 메서드에대해서알아보겠습니다. wait() 메서드는스스로자원에대한권한을포기하고대기상태로들어가는기능을구현한다. 생산자와소비자가있을때생산자가자원이없으면소비자를깨운뒤 wait() 를이용하여스스로실행불능상태로옮겨가고, 반대로소비자가자원이없으면생산자를깨운뒤스스로대기상태로들어가서자원이생기도록유도한다. wait() 를호출하기위해서는메서드를호출하는스레드가반드시자원의락 ( 권한 ) 을가지고있어야하고, 동기화 (synchronized) 블록안에서만호출이가능하다. wait() 된스레드를 notify() 를호출하여깨울때는자신이소유하고있는자원을기다리는스레드에한해서만깨우게된다

22 wait() 메서드는 wait(long timeout, int nanos); 와같이최대대기시간을 지정할수있어서주어진시간이지나면자동으로반환되게할수있다. Preemptive priority scheduling 구현 thread 에 priority 항목을추가하여우선순위를고려하게만들라는 문제입니다. 그런데자바언어에서는 thread를생성하면반드시우선순위인 priority가설정되어야하고 setpriority() 메서드를이용하여우선순위를부여할수있으며명시하지않았을경우에는기본적으로부모스레드와같은값을할당받게된다. 저희가분석한 Nachos Java 버전에서는 threads 폴더안에있는 Scheduler.java 와 PriorityScheduler.java 파일에우선순위를부여하는 코드가작성되어있으므로따로구현하지않고그부분의코드를분석 하도록하겠습니다. package nachos.threads; import nachos.machine.*; public abstract class Scheduler { public Scheduler() { Scheduler.java public abstract ThreadQueue newthreadqueue(boolean transferpriority); // ThreadQueue 라는추상메서드를설정하여자식클래스들이구현하도록강제함. public int getpriority(kthread thread) { // interrupt 가되지않도록 disabled() 로설정 return 0; public int getpriority() { return getpriority(kthread.currentthread()); // current thread 의우선순위를얻어낸다 29-21

23 public int geteffectivepriority(kthread thread) { // interrupt 가되지않도록 disabled() 로설정 return 0; public int geteffectivepriority() { return geteffectivepriority(kthread.currentthread()); // 현재스레드의유효한우선순위를얻는다. public void setpriority(kthread thread, int priority) { // interrupt 가되지않도록 disabled() 로설정 public void setpriority(int priority) { setpriority(kthread.currentthread(), priority); // 여기에서현재스레드의우선순위를설정한다 public boolean increasepriority() { return false; // 가능한범위안에서현재스레드의우선순위를높인다. public boolean decreasepriority() { return false; // 가능한범위안에서우선순위를낮추는메서드 PriorityScheduler.java package nachos.threads; import nachos.machine.*; import java.util.treeset; import java.util.hashset; import java.util.iterator; public class PriorityScheduler extends Scheduler { // 위에서분석한 Scheduler 를상속받았다. public PriorityScheduler() { // 디폴트생성자 public ThreadQueue newthreadqueue(boolean transferpriority) { return new PriorityQueue(transferPriority); // 부모클래스에서추상메서드로구현해놓은 ThreadQueue 메서드를오버라이딩했다

24 public int getpriority(kthread thread) { return getthreadstate(thread).getpriority(); // interrupt 가되지않도록 disabled() 로설정하고스레드의우선순위를얻는다. public int geteffectivepriority(kthread thread) { return getthreadstate(thread).geteffectivepriority(); public void setpriority(kthread thread, int priority) { Lib.assert(priority >= priorityminimum && priority <= prioritymaximum); getthreadstate(thread).setpriority(priority); public boolean increasepriority() { // 상속받은클래스의메서드를오버라이딩 boolean intstatus = Machine.interrupt().disable(); KThread thread = KThread.currentThread(); // 현재스레드를설정하고, int priority = getpriority(thread); // 스레드의우순순위를받고, if (priority == prioritymaximum) return false; // 만약에현재스레드의우선순위가 Maximum 이면더이상증가시킬수없으므로 false 를돌려준다. setpriority(thread, priority+1); // 우선순위를증가시킨다. Machine.interrupt().restore(intStatus); return true; public boolean decreasepriority() { // 메서드오버라이딩 boolean intstatus = Machine.interrupt().disable(); KThread thread = KThread.currentThread(); // 현재스레드를설정하고, int priority = getpriority(thread); // 스레드의우선순위를받고, if (priority == priorityminimum) return false; // 만약에현재스레드의우선순위가최소이면더이상감소시킬수없으므로 false 를돌려준다. setpriority(thread, priority-1); // 우선순위감소 Machine.interrupt().restore(intStatus); return true; 29-23

25 * 스레드가생성되면디폴트우선순위를갖고그값은 1 이다. * public static final int prioritydefault = 1; * * 최소우선순위 (priorityminumim) 값은 0 이다. * public static final int priorityminimum = 0; * * 최대우선순위값은 7 이다. * public static final int prioritymaximum = 7; protected ThreadState getthreadstate(kthread thread) { if (thread.schedulingstate == null) thread.schedulingstate = new ThreadState(thread); return (ThreadState) thread.schedulingstate; // ThreadQueue 는스레드를우선순위별로저장한다. protected class PriorityQueue extends ThreadQueue { PriorityQueue(boolean transferpriority) { this.transferpriority = transferpriority; public void waitforaccess(kthread thread) { getthreadstate(thread).waitforaccess(this); public void acquire(kthread thread) { getthreadstate(thread).acquire(this); public KThread nextthread() { // implement me return null; // 다음스레드가선택된다. // 다음스레드가선택된다. protected ThreadState picknextthread() { // implement me return null; 29-24

26 public void print() { public boolean transferpriority; protected class ThreadState { public ThreadState(KThread thread) { this.thread = thread; setpriority(prioritydefault); // 디폴트우선순위 (1) 로설정된다. // 관련된스레드의우선순위를돌려준다. public int getpriority() { return priority; // 스레드가사용가능한유효한우선순위를돌려준다. public int geteffectivepriority() { // implement me return priority; public void setpriority(int priority) { if (this.priority == priority) return; this.priority = priority; public void waitforaccess(priorityqueue waitqueue) { public void acquire(priorityqueue waitqueue) { // 객체의스레드 protected KThread thread; // 관련된스레드의우선순위 protected int priority; 29-25

27 Synchronization 실험문제 이번에제시된문제는동기화를구현하기위한문제로서 Worker가음식을만들면 Student들이음식을먹는프로그램을스레드들이교착상태에빠지지않도록만드는것입니다. 문제의해결을위해음식을만드는 Worker 스레드와음식을먹는 Student 스레드를구현한 Java 프로그램을작성하였습니다. Worker 는하나의스레드로구현하였고, 음식 (Food) 를만들고나서 wait() 로대기상태에들어갑니다. Student 는 3 개의스레드로구현하였고, 음식을놓고서로경쟁합니다. Worker는음식을만들고나서 notifyall() 을호출해서모든 Student들을깨웁니다. 깨어난 Student들은음식에대한권한을놓고서로경쟁하여권한을얻은스레드만음식을먹고다른스레드들은모두 get() 메서드에서멈추어져있는상태가됩니다. Student 스레드의 get() 메서드에서 Worker 스레드가음식을만들기를무한정기다리지않도록 100ms의시간마다스레드의종료조건을검사해서종료조건이참이면예외를발생시키도록하였습니다. 예외를받은스레드는이를처리한후종료하게됩니다. 이렇게함으로써 Worker 가만든음식을다른 Student 가모두먹어서 종료조건이참이되어도다른 Student 가종료하지못하는상황을막을 수있습니다. ( 그렇지않으면기아상태에빠질수있습니다 ) 음식은총 10개를만든다고가정하였고, 마지막 10번째의음식을먹는스레드만이종료조건을검사할수있고, 나머지 2개의스레드들은모두 get() 메서드를호출하는곳에서대기하게됩니다. 이때 get() 메서드내부에서는종료조건을점검해서예외를발생하고처리해서다른스레드도종료하게됩니다

28 아래에작성한 Java 프로그램소스는문제에서제시한모든조건을 구현하지는못했습니다. 하지만스레드들을작성하여동기화 (Synchronized) 시켰고, 기아가발생할만한요소를제거함으로서 deadlock 이나 starvation 이발생하지않고작동하도록하였습니다. 문제에서의도한 기본에는충실하게작성하였습니다. public class OurHome{ static class Worker extends Thread{ Food xres = null; OurHome.java public Worker(String name, Food res){ super(name); xres = res; public void run() { // 1 부터 10 까지의음식을만든다. for(int i=0; i<10; i++) { xres.put(i); System.out.println("Make Food : " + i); xres.stop(); static class Student extends Thread{ Food xres = null; public Student(String name, Food res){ super(name); xres = res; public void run() { // 학생스레드가실제로작동하는부분... 음식이있는동안먹는다. while(xres.qstop == false) { try { System.out.println( getname() + ", Eat food No. " + xres.get() ); catch(exception ex){ 29-27

29 static class Food{ boolean qavailable = false; int ndata; boolean qstop = false; Worker xproducer = null; public synchronized void stop(){ qstop = true; public synchronized int get() throws Exception{ while (qavailable == false) { try { // Worker 스레드가음식을만들때까지기다린다. // 만약 100ms 이상시간이지나면예외를발생하며반환된다. wait(100); catch (InterruptedException e){ // 만약종료조건이참이면음의값을반환한다. if (qstop == true) throw new Exception(); qavailable = false; // Worker 스레드를깨워서음식을만들도록한다. if(xproducer!= null && xproducer.isalive()) xproducer.interrupt(); return ndata; public synchronized void put(int value) { while (qavailable == true) { try { // Student 스레드가음식을먹을때까지기다린다. wait(); catch (InterruptedException e) { ndata = value; qavailable = true; // 모든 Student 스레드를깨운다. notifyall(); public void setproducer(worker prd) { xproducer = prd; 29-28

30 public static void main(string args[]){ Food res = new Food(); Worker prd = new Worker("Worker", res); Student eat = new Student("Student 1", res); Student eat2 = new Student("Student 2", res); Student eat3 = new Student("Student 3", res); res.setproducer(prd); prd.start(); eat.start(); eat2.start(); eat3.start(); try{ prd.join(); eat.join(); eat2.join(); eat3.join(); catch(exception ex){ 29-29

제11장 프로세스와 쓰레드

제11장 프로세스와 쓰레드 제9장자바쓰레드 9.1 Thread 기초 (1/5) 프로그램 명령어들의연속 (a sequence of instruction) 프로세스 / Thread 실행중인프로그램 (program in execution) 프로세스생성과실행을위한함수들 자바 Thread 2 9.1 Thread 기초 (2/5) 프로세스단위작업의문제점 프로세스생성시오버헤드 컨텍스트스위치오버헤드

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 23 장스레드 이번장에서학습할내용 스레드의개요 스레드의생성과실행 스레드상태 스레드의스케줄링 스레드간의조정 스레드는동시에여러개의프로그램을실행하는효과를냅니다. 멀티태스킹 멀티태스킹 (muli-tasking) 는여러개의애플리케이션을동시에실행하여서컴퓨터시스템의성능을높이기위한기법 스레드란? 다중스레딩 (multi-threading) 은하나의프로그램이동시에여러가지작업을할수있도록하는것

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 2... ( ). ( ). @ vs. logic data method variable behavior attribute method field Flow (Type), ( ) member @ () : C program Method A ( ) Method B ( ) Method C () program : Java, C++, C# data @ Program

More information

6주차.key

6주차.key 6, Process concept A program in execution Program code PCB (process control block) Program counter, registers, etc. Stack Heap Data section => global variable Process in memory Process state New Running

More information

Microsoft PowerPoint - lec12 [호환 모드]

Microsoft PowerPoint - lec12 [호환 모드] 스레드란? 스레드의상태 스레드스케줄링 동기화 스레드그룹 kkman@sangji.ac.kr 2 시작, 실행, 종료의순서를가지는제어흐름단위 단일스레딩시스템 : 오직하나의실행점 멀티스레딩시스템 : 다중의실행점 kkman@sangji.ac.kr 3 Concurrent Programming Multiprogramming System Multiprocessing System

More information

슬라이드 1

슬라이드 1 UNIT 16 예외처리 로봇 SW 교육원 3 기 최상훈 학습목표 2 예외처리구문 try-catch-finally 문을사용핛수있다. 프로그램오류 3 프로그램오류의종류 컴파일에러 (compile-time error) : 컴파일실행시발생 럮타임에러 (runtime error) : 프로그램실행시발생 에러 (error) 프로그램코드에의해서해결될수없는심각핚오류 ex)

More information

PowerPoint Presentation

PowerPoint Presentation Class - Property Jo, Heeseung 목차 section 1 클래스의일반구조 section 2 클래스선언 section 3 객체의생성 section 4 멤버변수 4-1 객체변수 4-2 클래스변수 4-3 종단 (final) 변수 4-4 멤버변수접근방법 section 5 멤버변수접근한정자 5-1 public 5-2 private 5-3 한정자없음

More information

PowerPoint Presentation

PowerPoint Presentation Package Class 1 Heeseung Jo 목차 section 1 패키지개요와패키지의사용 section 2 java.lang 패키지의개요 section 3 Object 클래스 section 4 포장 (Wrapper) 클래스 section 5 문자열의개요 section 6 String 클래스 section 7 StringBuffer 클래스 section

More information

Chapter #01 Subject

Chapter #01  Subject Device Driver March 24, 2004 Kim, ki-hyeon 목차 1. 인터럽트처리복습 1. 인터럽트복습 입력검출방법 인터럽트방식, 폴링 (polling) 방식 인터럽트서비스등록함수 ( 커널에등록 ) int request_irq(unsigned int irq, void(*handler)(int,void*,struct pt_regs*), unsigned

More information

JAVA PROGRAMMING 실습 08.다형성

JAVA PROGRAMMING 실습 08.다형성 2015 학년도 2 학기 1. 추상메소드 선언은되어있으나코드구현되어있지않은메소드 abstract 키워드사용 메소드타입, 이름, 매개변수리스트만선언 public abstract String getname(); public abstract void setname(string s); 2. 추상클래스 abstract 키워드로선언한클래스 종류 추상메소드를포함하는클래스

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 인터페이스, 람다식, 패키지 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 홈네트워킹 public interface RemoteControl { public void turnon(); // 가전제품을켠다. public void turnoff(); // 가전제품을끈다. 인터페이스를구현 public class Television

More information

JUNIT 실습및발표

JUNIT 실습및발표 JUNIT 실습및발표 JUNIT 접속 www.junit.org DownLoad JUnit JavaDoc API Document 를참조 JUNIT 4.8.1 다운로드 설치파일 (jar 파일 ) 을다운로드 CLASSPATH 를설정 환경변수에서설정 실행할클래스에서 import JUnit 설치하기 테스트실행주석 @Test Test 를실행할 method 앞에붙임 expected

More information

10주차.key

10주차.key 10, Process synchronization (concurrently) ( ) => critical section ( ) / =>, A, B / Race condition int counter; Process A { counter++; } Process B { counter ;.. } counter++ register1 = counter register1

More information

02 C h a p t e r Java

02 C h a p t e r Java 02 C h a p t e r Java Bioinformatics in J a va,, 2 1,,,, C++, Python, (Java),,, (http://wwwbiojavaorg),, 13, 3D GUI,,, (Java programming language) (Sun Microsystems) 1995 1990 (green project) TV 22 CHAPTER

More information

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1); void method() 2); void method1() public class Test 3); args) A 제 10 장상속 예제 1) ConstructorTest.java class Parent public Parent() super - default"); public Parent(int i) this("hello"); super(int) constructor" + i); public Parent(char c) this(); super(char) constructor

More information

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D> Power Java 제 8 장클래스와객체 I 이번장에서학습할내용 클래스와객체 객체의일생직접 메소드클래스를 필드작성해 UML 봅시다. QUIZ 1. 객체는 속성과 동작을가지고있다. 2. 자동차가객체라면클래스는 설계도이다. 먼저앞장에서학습한클래스와객체의개념을복습해봅시다. 클래스의구성 클래스 (class) 는객체의설계도라할수있다. 클래스는필드와메소드로이루어진다.

More information

Microsoft PowerPoint - CSharp-10-예외처리

Microsoft PowerPoint - CSharp-10-예외처리 10 장. 예외처리 예외처리개념 예외처리구문 사용자정의예외클래스와예외전파 순천향대학교컴퓨터학부이상정 1 예외처리개념 순천향대학교컴퓨터학부이상정 2 예외처리 오류 컴파일타임오류 (Compile-Time Error) 구문오류이기때문에컴파일러의구문오류메시지에의해쉽게교정 런타임오류 (Run-Time Error) 디버깅의절차를거치지않으면잡기어려운심각한오류 시스템에심각한문제를줄수도있다.

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스, 객체, 메소드 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 필드만있는클래스 텔레비젼 2 예제 1. 필드만있는클래스 3 예제 2. 여러개의객체생성하기 4 5 예제 3. 메소드가추가된클래스 public class Television { int channel; // 채널번호 int volume; // 볼륨 boolean

More information

Microsoft PowerPoint - 2강

Microsoft PowerPoint - 2강 컴퓨터과학과 김희천교수 학습개요 Java 언어문법의기본사항, 자료형, 변수와상수선언및사용법, 각종연산자사용법, if/switch 등과같은제어문사용법등에대해설명한다. 또한 C++ 언어와선언 / 사용방법이다른 Java의배열선언및사용법에대해서설명한다. Java 언어의효과적인활용을위해서는기본문법을이해하는것이중요하다. 객체지향의기본개념에대해알아보고 Java에서어떻게객체지향적요소를적용하고있는지살펴본다.

More information

untitled

untitled Embedded System Lab. II Embedded System Lab. II 2 RTOS Hard Real-Time vs Soft Real-Time RTOS Real-Time, Real-Time RTOS General purpose system OS H/W RTOS H/W task Hard Real-Time Real-Time System, Hard

More information

비긴쿡-자바 00앞부속

비긴쿡-자바 00앞부속 IT COOKBOOK 14 Java P r e f a c e Stay HungryStay Foolish 3D 15 C 3 16 Stay HungryStay Foolish CEO 2005 L e c t u r e S c h e d u l e 1 14 PPT API C A b o u t T h i s B o o k IT CookBook for Beginner Chapter

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 3 if, if else, if else if, switch case for, while, do while break, continue : System.in, args, JOptionPane for (,, ) @ vs. logic data method variable Data Data Flow (Type), ( ) @ Member field

More information

gnu-lee-oop-kor-lec06-3-chap7

gnu-lee-oop-kor-lec06-3-chap7 어서와 Java 는처음이지! 제 7 장상속 Super 키워드 상속과생성자 상속과다형성 서브클래스의객체가생성될때, 서브클래스의생성자만호출될까? 아니면수퍼클래스의생성자도호출되는가? class Base{ public Base(String msg) { System.out.println("Base() 생성자 "); ; class Derived extends Base

More information

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2 객체지향프로그래밍 IT CookBook, 자바로배우는쉬운자료구조 q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2 q 객체지향프로그래밍의이해 v 프로그래밍기법의발달 A 군의사업발전 1 단계 구조적프로그래밍방식 3 q 객체지향프로그래밍의이해 A 군의사업발전 2 단계 객체지향프로그래밍방식 4 q 객체지향프로그래밍의이해 v 객체란무엇인가

More information

JAVA PROGRAMMING 실습 09. 예외처리

JAVA PROGRAMMING 실습 09. 예외처리 2015 학년도 2 학기 예외? 프로그램실행중에발생하는예기치않은사건 예외가발생하는경우 정수를 0으로나누는경우 배열의크기보다큰인덱스로배열의원소를접근하는경우 파일의마지막부분에서데이터를읽으려고하는경우 예외처리 프로그램에문제를발생시키지않고프로그램을실행할수있게적절한조치를취하는것 자바는예외처리기를이용하여예외처리를할수있는기법제공 자바는예외를객체로취급!! 나뉨수를입력하시오

More information

Java ~ Java program: main() class class» public static void main(string args[])» First.java (main class ) /* The first simple program */ public class

Java ~ Java program: main() class class» public static void main(string args[])» First.java (main class ) /* The first simple program */ public class Linux JAVA 1. http://java.sun.com/j2se/1.4.2/download.html J2SE 1.4.2 SDK 2. Linux RPM ( 9 ) 3. sh j2sdk-1_4_2_07-linux-i586-rpm.bin 4. rpm Uvh j2sdk-1_4_2_07-linux-i586-rpm 5. PATH JAVA 1. vi.bash_profile

More information

5장.key

5장.key JAVA Programming 1 (inheritance) 2!,!! 4 3 4!!!! 5 public class Person {... public class Student extends Person { // Person Student... public class StudentWorker extends Student { // Student StudentWorker...!

More information

Cluster management software

Cluster management software 자바네트워크프로그래밍 (OCJP 국제공인자격취득중심 ) 충북대학교 최민 기본예제 예외클래스를정의하고사용하는예제 class NewException extends Exception { public class ExceptionTest { static void methoda() throws NewException { System.out.println("NewException

More information

스레드의우선순위 우선순위설정메소드 : void setpriority(int newpriority) newpriority 에설정할수있는등급 : 1( 가장낮은우선순위 ) 부터 10( 가장높은우선순위 ) 가장높은우선순위 : MAX_PRIORITY, 보통우선순위 : NORM_

스레드의우선순위 우선순위설정메소드 : void setpriority(int newpriority) newpriority 에설정할수있는등급 : 1( 가장낮은우선순위 ) 부터 10( 가장높은우선순위 ) 가장높은우선순위 : MAX_PRIORITY, 보통우선순위 : NORM_ 10 초동안사용자가입력하지않으면종료하는예제 ) import javax.swing.joptionpane; class AutoTermination { static boolean inputcheck = false; public static void main(string[] args) throws Exception { FirstThread th1 = new FirstThread();

More information

좀비프로세스 2

좀비프로세스 2 Signal & Inter-Process Communication Department of Computer Engineering Kyung Hee University. Choong Seon Hong 1 좀비프로세스 2 좀비프로세스 (zombie process) 좀비프로세스란프로세스종료후메모리상에서사라지지않는프로세스 좀비프로세스의생성이유. 자식프로세스는부모프로세스에게실행결과에대한값을반환해야한다.

More information

chap 5: Trees

chap 5: Trees 5. Threaded Binary Tree 기본개념 n 개의노드를갖는이진트리에는 2n 개의링크가존재 2n 개의링크중에 n + 1 개의링크값은 null Null 링크를다른노드에대한포인터로대체 Threads Thread 의이용 ptr left_child = NULL 일경우, ptr left_child 를 ptr 의 inorder predecessor 를가리키도록변경

More information

C# Programming Guide - Types

C# Programming Guide - Types C# Programming Guide - Types 최도경 lifeisforu@wemade.com 이문서는 MSDN 의 Types 를요약하고보충한것입니다. http://msdn.microsoft.com/enus/library/ms173104(v=vs.100).aspx Types, Variables, and Values C# 은 type 에민감한언어이다. 모든

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

Spring Boot/JDBC JdbcTemplate/CRUD 예제

Spring Boot/JDBC JdbcTemplate/CRUD 예제 Spring Boot/JDBC JdbcTemplate/CRUD 예제 오라클자바커뮤니티 (ojc.asia, ojcedu.com) Spring Boot, Gradle 과오픈소스인 MariaDB 를이용해서 EMP 테이블을만들고 JdbcTemplate, SimpleJdbcTemplate 을이용하여 CRUD 기능을구현해보자. 마리아 DB 설치는다음 URL 에서확인하자.

More information

Microsoft Word - FunctionCall

Microsoft Word - FunctionCall Function all Mechanism /* Simple Program */ #define get_int() IN KEYOARD #define put_int(val) LD A val \ OUT MONITOR int add_two(int a, int b) { int tmp; tmp = a+b; return tmp; } local auto variable stack

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 11 장상속 이번장에서학습할내용 상속이란? 상속의사용 메소드재정의 접근지정자 상속과생성자 Object 클래스 종단클래스 상속을코드를재사용하기위한중요한기법입니다. 상속이란? 상속의개념은현실세계에도존재한다. 상속의장점 상속의장점 상속을통하여기존클래스의필드와메소드를재사용 기존클래스의일부변경도가능 상속을이용하게되면복잡한 GUI 프로그램을순식간에작성

More information

(Microsoft PowerPoint - java2-lecture6.ppt [\310\243\310\257 \270\360\265\345])

(Microsoft PowerPoint - java2-lecture6.ppt [\310\243\310\257 \270\360\265\345]) 멀티태스킹과스레드개념 Thread & Multitasking 멀티태스킹 (Multi-tasking) 하나의응용프로그램이여러개의작업 ( 태스크 ) 을동시에처리 스레드 (Thread) 마치바늘이하나의실 (thread) 을가지고바느질하는것과자바의스레드는일맥상통함 514770-1 2017 년봄학기 5/10/2017 박경신 다림질하면서이어폰으로전화하는주부운전하면서화장하는운전자제품의판독과포장작업의두기능을갖춘기계

More information

untitled

untitled - -, (insert) (delete) - - (insert) (delete) (top ) - - (insert) (rear) (delete) (front) A A B top A B C top push(a) push(b) push(c) A B top pop() top A B D push(d) top #define MAX_STACK_SIZE 100 int

More information

rmi_박준용_final.PDF

rmi_박준용_final.PDF (RMI) - JSTORM http://wwwjstormpekr (RMI)- Document title: Document file name: Revision number: Issued by: Document Information (RMI)- rmi finaldoc Issue Date: Status:

More information

Abstract View of System Components

Abstract View of System Components 운영체제실습 - Synchronization - Real-Time Computing and Communications Lab. Hanyang University jtlim@rtcc.hanyang.ac.kr dhchoi@rtcc.hanyang.ac.kr beespjh@gmail.com Introduction 조교소개 이름 : 임정택 Tel : 010-4780

More information

스레드를적용하지않은결과와스레드를적용한결과의비교 1) 두개의작업을스레드를사용하지않고수행한예 ) : 순차작업 class ThreadTest2 { System.out.print("-");// 화면에 - 를출력하는작업 System.out.print(" ");// 화면에 를출력

스레드를적용하지않은결과와스레드를적용한결과의비교 1) 두개의작업을스레드를사용하지않고수행한예 ) : 순차작업 class ThreadTest2 { System.out.print(-);// 화면에 - 를출력하는작업 System.out.print( );// 화면에 를출력 실 (thread) 을이용한병렬처리 스레드 (thread) 는실을의미한다. 즉, 실하나에여러작업들이꿰어져서순서적으로처리된다. 그런데, 실을여러개 만들고이실에여러작업들을꿰어서이실들을순서적으로처리하게하면, 여러개의작업들이한꺼번에처리된다. 즉, 일정한단위시간당처리되는작업의수를증가시킬수있다. 스레드생성방법에대한예제 ) class ThreadTest1 { ThreadClass1

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 오류처리 손시운 ssw5176@kangwon.ac.kr 오류메시지를분석한다. 오류메시지에서많은내용을알수있다. 2 디버깅 디버거를사용하면프로그램에서쉽게오류를감지하고진단할수있다. 디버거는중단점을설정하여서프로그램의실행을제어할수있으며문장 단위로실행하거나변수의값을살펴볼수있다. 3 이클립스에서디버깅 4 이클립스에서디버깅 5 이클립스의디버깅명령어 6 예외처리

More information

Design Issues

Design Issues 11 COMPUTER PROGRAMMING INHERIATANCE CONTENTS OVERVIEW OF INHERITANCE INHERITANCE OF MEMBER VARIABLE RESERVED WORD SUPER METHOD INHERITANCE and OVERRIDING INHERITANCE and CONSTRUCTOR 2 Overview of Inheritance

More information

Microsoft PowerPoint - Java7.pptx

Microsoft PowerPoint - Java7.pptx HPC & OT Lab. 1 HPC & OT Lab. 2 실습 7 주차 Jin-Ho, Jang M.S. Hanyang Univ. HPC&OT Lab. jinhoyo@nate.com HPC & OT Lab. 3 Component Structure 객체 (object) 생성개념을이해한다. 외부클래스에대한접근방법을이해한다. 접근제어자 (public & private)

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Lab 4 ADT Design 클래스로정의됨. 모든객체들은힙영역에할당됨. 캡슐화 (Encapsulation) : Data representation + Operation 정보은닉 (Information Hiding) : Opertion부분은가려져있고, 사용자가 operation으로만사용가능해야함. 클래스정의의형태 public class Person { private

More information

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 (   ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각 JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( http://java.sun.com/javase/6/docs/api ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각선의길이를계산하는메소드들을작성하라. 직사각형의가로와세로의길이는주어진다. 대각선의길이는 Math클래스의적절한메소드를이용하여구하라.

More information

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345])

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345]) 예외와예외클래스 예외처리 514760-1 2016 년가을학기 12/08/2016 박경신 오류의종류 에러 (Error) 하드웨어의잘못된동작또는고장으로인한오류 에러가발생되면 JVM실행에문제가있으므로프로그램종료 정상실행상태로돌아갈수없음 예외 (Exception) 사용자의잘못된조작또는개발자의잘못된코딩으로인한오류 예외가발생되면프로그램종료 예외처리 추가하면정상실행상태로돌아갈수있음

More information

Microsoft PowerPoint - java2-lecture6.ppt [호환 모드]

Microsoft PowerPoint - java2-lecture6.ppt [호환 모드] Multi-tasking vs Thread Thread & Multitasking 멀티태스킹 (Multi-tasking) 하나의응용프로그램이여러개의작업 ( 태스크 ) 을동시에처리 스레드 (Thread) 마치바늘이하나의실 (thread) 을가지고바느질하는것과자바의스레드는일맥상통함 514770 2018 년가을학기 11/19/2018 박경신 다림질하면서이어폰으로전화하는주부운전하면서화장하는운전자제품의판독과포장작업의두기능을갖춘기계

More information

C++ Programming

C++ Programming C++ Programming 예외처리 Seo, Doo-okok clickseo@gmail.com http://www.clickseo.com 목 차 예외처리 2 예외처리 예외처리 C++ 의예외처리 예외클래스와객체 3 예외처리 예외를처리하지않는프로그램 int main() int a, b; cout > a >> b; cout

More information

자바 프로그래밍

자바 프로그래밍 5 (kkman@mail.sangji.ac.kr) (Class), (template) (Object) public, final, abstract [modifier] class ClassName { // // (, ) Class Circle { int radius, color ; int x, y ; float getarea() { return 3.14159

More information

Microsoft PowerPoint - Lecture_Note_7.ppt [Compatibility Mode]

Microsoft PowerPoint - Lecture_Note_7.ppt [Compatibility Mode] Unix Process Department of Computer Engineering Kyung Hee University. Choong Seon Hong 1 유닉스기반다중서버구현방법 클라이언트들이동시에접속할수있는서버 서비스를동시에처리할수있는서버프로세스생성을통한멀티태스킹 (Multitasking) 서버의구현 select 함수에의한멀티플렉싱 (Multiplexing)

More information

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

Microsoft PowerPoint 자바-기본문법(Ch2).pptx 자바기본문법 1. 기본사항 2. 자료형 3. 변수와상수 4. 연산자 1 주석 (Comments) 이해를돕기위한설명문 종류 // /* */ /** */ 활용예 javadoc HelloApplication.java 2 주석 (Comments) /* File name: HelloApplication.java Created by: Jung Created on: March

More information

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx 2018 학년도 1 학기 JAVA 프로그래밍 II 514760-1 2018 년봄학기 5/10/2018 박경신 Lab#1 (ImageTest) Lab#1 은영상파일 (Image) 을읽어서정보를출력 Java Tutorials Lesson: Working with Images https://docs.oracle.com/javase/tutorial/2d/images/index.html

More information

JMF3_심빈구.PDF

JMF3_심빈구.PDF JMF JSTORM http://wwwjstormpekr Issued by: < > Revision: Document Information Document title: Document file name: Revision number: Issued by: JMF3_ doc Issue Date:

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 인터페이스 배효철 th1g@nate.com 1 목차 인터페이스의역할 인터페이스선언 인터페이스구현 인터페이스사용 타입변환과다형성 인터페이스상속 디폴트메소드와인터페이스확장 2 인터페이스의역할 인터페이스란? 개발코드와객체가서로통신하는접점 개발코드는인터페이스의메소드만알고있으면 OK 인터페이스의역할 개발코드가객체에종속되지않게 -> 객체교체할수있도록하는역할 개발코드변경없이리턴값또는실행내용이다양해질수있음

More information

PowerPoint Presentation

PowerPoint Presentation Package Class 3 Heeseung Jo 목차 section 1 패키지개요와패키지의사용 section 2 java.lang 패키지의개요 section 3 Object 클래스 section 4 포장 (Wrapper) 클래스 section 5 문자열의개요 section 6 String 클래스 section 7 StringBuffer 클래스 section

More information

ABC 11장

ABC 11장 12 장고급응용 0 수행중인프로그램 프로세스 모든프로세스는유일한프로세스식별번호 (PID) 를가짐 유닉스에서는 ps 명령을사용하여프로세스목록을볼수있음 12-1 프로세스 $ ps -aux USER PID %CPU %MEM SZ RSS TT STAT START TIME COMMAND blufox 17725 34.0 1.6 146 105 i2 R 15:13 0:00

More information

Spring Data JPA Many To Many 양방향 관계 예제

Spring Data JPA Many To Many 양방향 관계 예제 Spring Data JPA Many To Many 양방향관계예제 오라클자바커뮤니티 (ojc.asia, ojcedu.com) 엔티티매핑 (Entity Mapping) M : N 연관관계 사원 (Sawon), 취미 (Hobby) 는다 : 다관계이다. 사원은여러취미를가질수있고, 하나의취미역시여러사원에할당될수있기때문이다. 보통관계형 DB 에서는다 : 다관계는 1

More information

Microsoft PowerPoint - 04-UDP Programming.ppt

Microsoft PowerPoint - 04-UDP Programming.ppt Chapter 4. UDP Dongwon Jeong djeong@kunsan.ac.kr http://ist.kunsan.ac.kr/ Dept. of Informatics & Statistics 목차 UDP 1 1 UDP 개념 자바 UDP 프로그램작성 클라이언트와서버모두 DatagramSocket 클래스로생성 상호간통신은 DatagramPacket 클래스를이용하여

More information

JAVA PROGRAMMING 실습 05. 객체의 활용

JAVA PROGRAMMING 실습 05. 객체의 활용 public class Person{ public String name; public int age; } public Person(){ } public Person(String s, int a){ name = s; age = a; } public String getname(){ return name; } @ 객체의선언 public static void main(string

More information

JVM 메모리구조

JVM 메모리구조 조명이정도면괜찮조! 주제 JVM 메모리구조 설미라자료조사, 자료작성, PPT 작성, 보고서작성. 발표. 조장. 최지성자료조사, 자료작성, PPT 작성, 보고서작성. 발표. 조원 이용열자료조사, 자료작성, PPT 작성, 보고서작성. 이윤경 자료조사, 자료작성, PPT작성, 보고서작성. 이수은 자료조사, 자료작성, PPT작성, 보고서작성. 발표일 2013. 05.

More information

1

1 1 1....6 1.1...6 2. Java Architecture...7 2.1 2SDK(Software Development Kit)...8 2.2 JRE(Java Runtime Environment)...9 2.3 (Java Virtual Machine, JVM)...10 2.4 JVM...11 2.5 (runtime)jvm...12 2.5.1 2.5.2

More information

파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter

파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter 파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter 클래스의사용법은다음과같다. PrintWriter writer = new PrintWriter("output.txt");

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 4 (Object) (Class) (Instance) (Method) (Constructor) Memory 1 UML 1 @ & 1 (Real World) (Software World) @ &.. () () @ & 2 (Real World) (Software World) OOA/ Modeling Abstraction Instantiation

More information

No Slide Title

No Slide Title 상속 이충기 명지대학교컴퓨터공학과 상속 Q: 건설회사는기존아파트와조금다르거나추가적인특징들을가진새아파트를지을때어떻게하는가? A: 2 상속 상속 (inheritance) 은클래스들을연관시키는자연스럽고계층적인방법이다. 상속은객체지향프로그래밍의가장중요한개념중의하나이다. 상속은 은 이다 라는관계 (is-a relationship) 를나타낸다. 이관계를적용하여클래스들을상하관계로연결하는것이상속이다.

More information

Network Programming

Network Programming Part 5 확장된 Network Programming 기술 1. Remote Procedure Call 2. Remote Method Invocation 3. Object Request Broker 2. Java RMI

More information

Microsoft PowerPoint - RMI.ppt

Microsoft PowerPoint - RMI.ppt ( 분산통신실습 ) RMI RMI 익히기 1. 분산환경에서동작하는 message-passing을이용한 boundedbuffer 해법프로그램을실행해보세요. 소스코드 : ftp://211.119.245.153 -> os -> OSJavaSources -> ch15 -> rmi http://marvel el.incheon.ac.kr의 Information Unix

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 제 5 장생성자와접근제어 1. 객체지향기법을이해한다. 2. 클래스를작성할수있다. 3. 클래스에서객체를생성할수있다. 4. 생성자를이용하여객체를초기화할수 있다. 5. 접근자와설정자를사용할수있다. 이번장에서만들어볼프로그램 생성자 생성자 (constructor) 는초기화를담당하는함수 생성자가필요한이유 #include using namespace

More information

10.0pt1height.7depth.3width±â10.0pt1height.7depth.3widthÃÊ10.0pt1height.7depth.3widthÅë10.0pt1height.7depth.3width°è10.0pt1height.7depth.3widthÇÁ10.0pt1height.7depth.3width·Î10.0pt1height.7depth.3width±×10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width¹Ö pt1height.7depth.3widthŬ10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width½º, 10.0pt1height.7depth.3width°´10.0pt1height.7depth.3widthü, 10.0pt1height.7depth.3widthº¯10.0pt1height.7depth.3width¼ö, 10.0pt1height.7depth.3width¸Þ10.0pt1height.7depth.3width¼Ò10.0pt1height.7depth.3widthµå

10.0pt1height.7depth.3width±â10.0pt1height.7depth.3widthÃÊ10.0pt1height.7depth.3widthÅë10.0pt1height.7depth.3width°è10.0pt1height.7depth.3widthÇÁ10.0pt1height.7depth.3width·Î10.0pt1height.7depth.3width±×10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width¹Ö pt1height.7depth.3widthŬ10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width½º, 10.0pt1height.7depth.3width°´10.0pt1height.7depth.3widthü, 10.0pt1height.7depth.3widthº¯10.0pt1height.7depth.3width¼ö, 10.0pt1height.7depth.3width¸Þ10.0pt1height.7depth.3width¼Ò10.0pt1height.7depth.3widthµå 기초통계프로그래밍 클래스, 객체, 변수, 메소드 hmkang@hallym.ac.kr 금융정보통계학과 강희모 ( 금융정보통계학과 ) 기초통계프로그래밍 1 / 26 자바구성파일 소스파일 소스파일 : 사용자가직접에디터에입력하는파일로자바프로그램언어가제공하는형식으로제작 소스파일의확장자는.java 임 컴파일 : javac 명령어를이용하여프로그래머가만든소스파일을컴파일하여실행파일.class

More information

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Function) 1. 함수의개념 입력에대해적절한출력을발생시켜주는것 내가 ( 프로그래머 ) 작성한명령문을연산, 처리, 실행해주는부분 ( 모듈 ) 자체적으로실행되지않으며,

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 실습 1 배효철 th1g@nate.com 1 목차 조건문 반복문 System.out 구구단 모양만들기 Up & Down 2 조건문 조건문의종류 If, switch If 문 조건식결과따라중괄호 { 블록을실행할지여부결정할때사용 조건식 true 또는 false값을산출할수있는연산식 boolean 변수 조건식이 true이면블록실행하고 false 이면블록실행하지않음 3

More information

12-file.key

12-file.key 11 (String).. java.lang.stringbuffer. s String s = "abcd"; s = s + "e"; a b c d e a b c d e ,., "910359,, " "910359" " " " " (token) (token),, (delimiter). java.util.stringtokenizer String s = "910359,,

More information

05-class.key

05-class.key 5 : 2 (method) (public) (private) (interface) 5.1 (Method), (public method) (private method) (constructor), 3 4 5.2 (client). (receiver)., System.out.println("Hello"); (client object) (receiver object)

More information

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드] - Socket Programming in Java - 목차 소켓소개 자바에서의 TCP 프로그램작성방법 주요클래스와메소드 HTTP 프로토콜을이용한예제 에코프로그램 Q/A 에코프로그램 - EchoServer 에코프로그램 - EchoClient TCP Programming 1 소켓소개 IP, Port, and Socket 포트 (Port): 전송계층에서통신을수행하는응용프로그램을찾기위한주소

More information

[ 프로젝트이름 ] : Project_Car [ 프로젝트를만든목적 ] : 임의의자동차판매소가있다고가정하고, 고객이원하는자동차의각부분을 Java 를이용하여객 체로생성하고, 그것을제어하는메소드를이용하여자동차객체를생성하는것이목표이다. [ 프로젝트패키지와클래스의내용설명 ] [

[ 프로젝트이름 ] : Project_Car [ 프로젝트를만든목적 ] : 임의의자동차판매소가있다고가정하고, 고객이원하는자동차의각부분을 Java 를이용하여객 체로생성하고, 그것을제어하는메소드를이용하여자동차객체를생성하는것이목표이다. [ 프로젝트패키지와클래스의내용설명 ] [ [ 프로젝트이름 ] : Project_Car [ 프로젝트를만든목적 ] : 임의의자동차판매소가있다고가정하고, 고객이원하는자동차의각부분을 Java 를이용하여객 체로생성하고, 그것을제어하는메소드를이용하여자동차객체를생성하는것이목표이다. [ 프로젝트패키지와클래스의내용설명 ] [Car 패키지 ] : Body, Engine, Seat, Tire, SpeedGauge, Vendor,

More information

1장. 유닉스 시스템 프로그래밍 개요

1장.  유닉스 시스템 프로그래밍 개요 Unix 프로그래밍및실습 7 장. 시그널 - 과제보충 응용과제 1 부모프로세스는반복해서메뉴를출력하고사용자로부터주문을받아자식프로세스에게주문내용을알린다. (SIGUSR1) ( 일단주문을받으면음식이완료되기전까지 SIGUSR1 을제외한다른시그널은모두무시 ) timer 자식프로세스는주문을받으면조리를시작한다. ( 일단조리를시작하면음식이완성되기전까지 SIGALARM 을제외한다른시그널은모두무시

More information

Microsoft Word - java19-1-midterm-answer.doc

Microsoft Word - java19-1-midterm-answer.doc 중간고사 담당교수 : 단국대학교응용컴퓨터공학박경신 답은반드시답안지에기술할것. 공간이부족할경우반드시답안지몇쪽의뒤에있다고명기한후기술할것. 그외의경우의답안지뒤쪽이나연습지에기술한내용은답안으로인정안함. 답에는반드시네모를쳐서확실히표시할것. 답안지에학과, 학번, 이름외에본인의암호 (4자리숫자 ) 를기입하면성적공고시학번대신암호를 사용할것임. 1. 다음질문에답을하라. (55

More information

Microsoft PowerPoint - 03-TCP Programming.ppt

Microsoft PowerPoint - 03-TCP Programming.ppt Chapter 3. - Socket in Java - 목차 소켓소개 자바에서의 프로그램작성방법 주요클래스와메소드 HTTP 프로토콜을이용한예제 에코프로그램 에코프로그램 - EchoServer 에코프로그램 - EchoClient Q/A 1 1 소켓소개 IP,, and Socket 포트 (): 전송계층에서통신을수행하는응용프로그램을찾기위한주소 소켓 (Socket):

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 9 장생성자와접근제어 이번장에서학습할내용 생성자 정적변수 정적메소드 접근제어 this 클래스간의관계 객체가생성될때초기화를담당하는생성자에대하여살펴봅니다. 생성자 생성자 (contructor): 객체가생성될때에필드에게초기값을제공하고필요한초기화절차를실행하는메소드 생성자의예 class Car { private String color; // 색상

More information

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D> 리눅스 오류처리하기 2007. 11. 28 안효창 라이브러리함수의오류번호얻기 errno 변수기능오류번호를저장한다. 기본형 extern int errno; 헤더파일 라이브러리함수호출에실패했을때함수예 정수값을반환하는함수 -1 반환 open 함수 포인터를반환하는함수 NULL 반환 fopen 함수 2 유닉스 / 리눅스 라이브러리함수의오류번호얻기 19-1

More information

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public Chapter 9 Lab 문제정답 1. public class Circle private double radius; static final double PI=3.141592; // PI 이름으로 3.141592 로초기화된정적상수 (1) public Circle(double r) radius = r; (2) public double getradius() return

More information

작성자 : 김성박\(삼성 SDS 멀티캠퍼스 전임강사\)

작성자 : 김성박\(삼성 SDS 멀티캠퍼스 전임강사\) Session 을이용한현재로그인한사용자의 숫자구하기 작성자 : 김성박 ( 삼성 SDS 멀티캠퍼스전임강사 ) email : urstory@nownuri.net homepage : http://sunny.sarang.net - 본문서는http://sunny.sarang.net JAVA강좌란 혹은 http://www.javastudy.co.kr 의 칼럼 란에서만배포합니다.

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 1,..... @ 1 Green Project 1991 Oak Java 1995. 5 December '90 by Patrick Naughton, Mike Sheridan and James Gosling Embedded in various consumer electronic device 1992. 9. 3 Star 7 1993 www portability

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 제 11 장상속 1. 상속의개념을이해한다. 2. 상속을이용하여자식클래스를작성할수있다. 3. 상속과접근지정자와의관계를이해한다. 4. 상속시생성자와소멸자가호출되는순서를이해한다. 이번장에서만들어볼프로그램 class Circle { int x, y; int radius;... class Rect { int x, y; int width, height;... 중복 상속의개요

More information

Microsoft PowerPoint - lec2.ppt

Microsoft PowerPoint - lec2.ppt 2008 학년도 1 학기 상지대학교컴퓨터정보공학부 고광만 강의내용 어휘구조 토큰 주석 자료형기본자료형 참조형배열, 열거형 2 어휘 (lexicon) 어휘구조와자료형 프로그램을구성하는최소기본단위토큰 (token) 이라부름문법적으로의미있는최소의단위컴파일과정의어휘분석단계에서처리 자료형 자료객체가갖는형 구조, 개념, 값, 연산자를정의 3 토큰 (token) 정의문법적으로의미있는최소의단위예,

More information

쉽게

쉽게 Power Java 제 4 장자바프로그래밍기초 이번장에서학습할내용 자바프로그램에대한기초사항을학습 자세한내용들은추후에. Hello.java 프로그램 주석 주석 (comment): 프로그램에대한설명을적어넣은것 3 가지타입의주석 클래스 클래스 (class): 객체를만드는설계도 ( 추후에학습 ) 자바프로그램은클래스들로구성된다. 그림 4-1. 자바프로그램의구조 클래스정의

More information

Microsoft PowerPoint - o6.pptx

Microsoft PowerPoint - o6.pptx Dining-Philosophers Problem 세마포사용 6.8 모니터 (Monitors) Semaphore chopstick[5] = {1,1,1,1,1 ; // initially all values are 1 Philosopher i while (true) { P(chopStick[i]); // get left chopstick P(chopStick[(i+1)

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 클래스와메소드심층연구 ( 실습 ) 손시운 ssw5176@kangwon.ac.kr 예제 1. 접근제어 class A { private int a; int b; public int c; // 전용 // 디폴트 // 공용 public class Test { public static void main(string args[]) { A obj = new

More information

PowerPoint Presentation

PowerPoint Presentation public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum +

More information

PowerPoint Presentation

PowerPoint Presentation 객체지향프로그래밍 오류처리 손시운 ssw5176@kangwon.ac.kr 오류메시지를분석한다. 오류메시지에서많은내용을알수있다. 2 디버깅 디버거를사용하면프로그램에서쉽게오류를감지하고진단할수있다. 디버거는중단점을설정하여서프로그램의실행을제어할수있으며문장 단위로실행하거나변수의값을살펴볼수있다. 3 이클립스에서디버깅 4 이클립스에서디버깅 5 이클립스의디버깅명령어 6 예외처리

More information

슬라이드 1

슬라이드 1 마이크로컨트롤러 2 (MicroController2) 2 강 ATmega128 의 external interrupt 이귀형교수님 학습목표 interrupt 란무엇인가? 기본개념을알아본다. interrupt 중에서가장사용하기쉬운 external interrupt 의사용방법을학습한다. 1. Interrupt 는왜필요할까? 함수동작을추가하여실행시키려면? //***

More information

JAVA PROGRAMMING 실습 07. 상속

JAVA PROGRAMMING 실습 07. 상속 상속 부모클래스에정의된필드와메소드를자식클래스가물려받는것 슈퍼클래스 (superclass) 특성을물려주는상위클래스 서브클래스 (subclass) 특성을물려받는하위클래스 슈퍼클래스에자신만의특성 ( 필드, 메소드 ) 추가 슈퍼클래스의특성 ( 메소드 ) 을수정 = 오버라이딩구체화 class Phone 전화걸기전화받기 class MobilePhone 전화걸기전화받기무선기지국연결배터리충전하기

More information

쉽게 풀어쓴 C 프로그래밍

쉽게 풀어쓴 C 프로그래밍 Power Java 제 7 장클래스와객체 이번장에서학습할내용 객체지향이란? 객체 메시지 클래스 객체지향의장점 String 클래스 객체지향개념을완벽하게이해해야만객체지향설계의이점을활용할수있다. 실제세계는객체로이루어진다. 객체지향이란? 실제세계를모델링하여소프트웨어를개발하는방법 절차지향과객체지향 절차지향프로그래밍 (procedural programming): 문제를해결하는절차를중요하게생각하는방법

More information

쉽게 풀어쓴 C 프로그래밊

쉽게 풀어쓴 C 프로그래밊 Power Java 제 27 장데이터베이스 프로그래밍 이번장에서학습할내용 자바와데이터베이스 데이터베이스의기초 SQL JDBC 를이용한프로그래밍 변경가능한결과집합 자바를통하여데이터베이스를사용하는방법을학습합니다. 자바와데이터베이스 JDBC(Java Database Connectivity) 는자바 API 의하나로서데이터베이스에연결하여서데이터베이스안의데이터에대하여검색하고데이터를변경할수있게한다.

More information

Microsoft PowerPoint - o6.pptx

Microsoft PowerPoint - o6.pptx Dining-Philosophers Problem 세마포사용 Semaphore chopstick[5] = {1,1,1,1,1} ; // initially all values are 1 Philosopher i while (true) { P(chopStick[i]); // get left chopstick P(chopStick[(i+1) % 5]); // get

More information

Chap12

Chap12 12 12Java RMI 121 RMI 2 121 RMI 3 - RMI, CORBA 121 RMI RMI RMI (remote object) 4 - ( ) UnicastRemoteObject, 121 RMI 5 class A - class B - ( ) class A a() class Bb() 121 RMI 6 RMI / 121 RMI RMI 1 2 ( 7)

More information

교육자료

교육자료 THE SYS4U DODUMENT Java Reflection & Introspection 2012.08.21 김진아사원 2012 SYS4U I&C All rights reserved. 목차 I. 개념 1. Reflection 이란? 2. Introspection 이란? 3. Reflection 과 Introspection 의차이점 II. 실제사용예 1. Instance의생성

More information

09-interface.key

09-interface.key 9 Database insert(record r): boolean find(key k): Record 1 Record getkey(): Key * Record Key Database.? Key equals(key y): boolean Database insert(record r): boolean find(key k): Record * Database OK 1

More information