Subject : Java Multi Thread 구현 예
Solution Description:
=====================
쓰레드란 자신만의 제어흐름을 갖고서 독립적으로 실행되는 열들을
쓰레드라고 하며 한 프로그램에서 여러개의 쓰레드를 실행할 수 있다면
다중 쓰레딩이라 한다.
다중프로그래밍은 여러개의 프로그램을 논리적으로 동시에 실행하는 것이며
다중쓰레딩은 한 프로세스의 context내에서 동시성을 제공하고 다중프로그래밍은
프로세스간의 동시성을 제공한다는 점에서 다르다.
Multi Programming
----------------- --------
| Program 1 | | CPU 1 |
|-----------------| --------
| . | .
| . |<-------------------- .
| . | .
|-----------------| --------
| Program n | | CPU m |
| | --------
------------------
Multi Threading
------------------------ --------
| Program 1 (Thread 1-1) | | CPU 1 |
| (Thread 1-i) | --------
|------------------------|
| . | .
| . |<-------------- .
| . | .
|------------------------| --------
| Program n (Thread n-1) | | CPU m |
| (Thread n-i) | --------
-------------------------
- Thread 응용 프로그램 예제
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
class TwoThreadsTest {
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
- 동기화된 Thread 응용 프로그램 예제
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) {
}
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number + " got: " + value);
}
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
----------------------------------------------------------------------------
Revision History
작성일자 : 97.07.19
작성자 : 이민호
수정일자 :
수정자 :