
하나의 thread만 사용하면 하나의 처리를 끝낸 후 다른 처리를 시작할 수 있다. multi-thread를 사용하면 서버가 request를 받으면 데이터 처리를 thread에 맡기고 서버는 다시 listening 상태를 유지하며 request를 받을 수 있다. 하나의 thread를 사용한다면 서버는 request 받은 내용을 모두 처리한 후, 다시 listening 상태가 될 수 있기 때문에 여러 개의 request를 동시에 처리할 수 없게 된다.
class MyThread1 extends Thread {
public void run() {
try {
while (true) {
System.out.println("Hello, Thread!");
Thread.sleep(500);
}
}
catch (InterruptedException ie) {
System.out.println("I'm interrupted");
}
}
}
public class ThreadExample1 {
public static final void main(String[] args) {
MyThread1 thread = new MyThread1();
thread.start(); // run method를 호출
System.out.println("Hello, My Child!"); // 부모 thread가 출력
}
}
class MyThread2 implements Runnable {
public void run() {
try {
while (true) {
System.out.println("Hello, Runnable!");
Thread.sleep(500);
}
}
catch (InterruptedException ie) {
System.out.println("I'm interrupted");
}
}
}
public class ThreadExample2 {
public static final void main(String[] args) {
Thread thread = new Thread(new MyThread2());
thread.start();
System.out.println("Hello, My Runnable Child!");
}
}
public class ThreadExample3 {
public static final void main(String[] args) {
Runnable task = () -> {
try {
while (true) {
System.out.println("Hello, Lambda Runnable!");
Thread.sleep(500);
}
}
catch (InterruptedException ie) {
System.out.println("I'm interrupted");
}
};
Thread thread = new Thread(task);
thread.start();
System.out.println("Hello, My Labmda child!");
}
}
별도 클래스를 선언하여 생성자에 인스턴스를 넘기는 것이 아닌 람다 인스턴스를 넘기는 방법
public class ThreadExample4 {
public static final void main(String[] args) {
Runnable task = () -> {
for (int i=0;i<5;i++)
System.out.println("Hello, Lambda Runnable!");
}
};
Thread thread = new Thread(task);
thread.start();
try {
thread.join();
}
catch (InterruptedException ie) {
System.out.println("Parent thread is interrupted!");
}
System.out.println("Hello, My Joined Child!");
}
public class ThreadExample5 {
public static final void main(String[] args) throws InterruptedException {
Runnable task = () -> {
try {
while (true) {
System.out.println("Hello, Lambda Runnable!");
Thread.sleep(100);
}
}
catch (InterruptedException ie) {
System.out.println("I'm interrupted");
}
};
Thread thread = new Thread(task);
thread.start();
Thread.sleep(500);
thread.interrupt();
System.out.println("Hello, My Interrupted Child!");
}
}
기능은 좋지만 문제가 너무 어려워짐 -> context switching 횟수가 줄어듬
어떤 시스템을 개선하여 전체 작업 중 P%의 부분에서 S배의 성능이 향상되었을 때, 전체 시스템 성능향상을 정의함
ex)
어떤 작업의 40%에 해당하는 부분의 속도를 2배로 늘릴 수 있다면, , 이며, 최대성능 향상은 가 된다.