반응형
suspend()
- sleep()처럼 쓰레드를 멈추게 함
- resume()을 호출해야 다시 실행대기 상태가 됨
resume()
- suspend()에 의해 정지된 쓰레드를 다시 실행대기 상태로 전환
stop()
- 호출되는 즉시 쓰레드 종료
위 메소드들은 교착상태(deadlock)를 일으키기 쉽게 작성되어있어 사용이 권장되지 않음
|
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
|
package thread;
// Runnable인터페이스 상속해 쓰레드 구현
class RunImplEx15 implements Runnable {
@Override
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
}
}
}
public class ThreadEx15 {
public static void main(String[] args) {
RunImplEx15 r = new RunImplEx15();;
// Runnable인터페이스로 구현한 쓰레드는 Thread클래스를 통해야 함
Thread th1 = new Thread(r, "*");
Thread th2 = new Thread(r, "**");
Thread th3 = new Thread(r, "***");
// 쓰레드 시작
th1.start();
th2.start();
th3.start();
try {
Thread.sleep(2000);
th1.suspend(); // th1쓰레드 잠시중단
Thread.sleep(2000);
th2.suspend();
Thread.sleep(3000);
th1.resume(); // th1쓰레드 재실행
Thread.sleep(3000);
th1.stop(); // th1쓰레드 종료
th2.stop(); // th2쓰레드 종료
Thread.sleep(2000);
th3.stop(); // th3쓰레드 종료
} catch(InterruptedException e) {}
}
}
|
cs |
간단한 위 메소드들의 사용법
|
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
|
package thread;
// Runnable인터페이스 상속해 쓰레드 구현
class Thread17_1 implements Runnable {
// boolean형 변수를 선언해 이들을 사용해 쓰레드의 작업을 중지시켰다가 재개하거나 종료되도록 함
volatile boolean suspended = false;
volatile boolean stopped = false;
Thread th;
// 생성자, 생성자를 통해 이름을 가진 쓰레드를 생성함
Thread17_1(String name) {
th = new Thread(this,name); // Thread(Runnable r, String name)
}
@Override
public void run() {
while(!stopped) {
if(!suspended) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
}
}
System.out.println(Thread.currentThread().getName() + " - stopped");
}
public void start() { th.start(); }
public void suspend() { suspended = true; }
public void stop() { stopped = true; }
public void resume() { suspended = false; }
}
public class ThreadEx17 {
public static void main(String[] args) {
Thread17_1 th1 = new Thread17_1("*");
Thread17_1 th2 = new Thread17_1("**");
Thread17_1 th3 = new Thread17_1("***");
// 쓰레드 시작
th1.start();
th2.start();
th3.start();
try {
Thread.sleep(2000);
th1.suspend(); // th1쓰레드 잠시중단
Thread.sleep(2000);
th2.suspend();
Thread.sleep(3000);
th1.resume(); // th1쓰레드 재실행
Thread.sleep(3000);
th1.stop(); // th1쓰레드 종료
th2.stop(); // th2쓰레드 종료
Thread.sleep(2000);
th3.stop(); // th3쓰레드 종료
} catch(InterruptedException e) {}
}
}
|
cs |
기능을 좀 더 보완하고 객체지향적으로 작성됨
yield()
- 쓰레드 자신에게 주어진 실행시간을 다음 차례의 쓰레드에게 양보
yield()와 interrupt()를 적절히 사용하면, 프로그램의 응답성을 높이고 보다 효율적인 실행을 가능케 할 수 있음
|
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
|
package thread;
// Runnable인터페이스 상속해 쓰레드 구현
class Thread18_1 implements Runnable {
// boolean형 변수를 선언해 이들을 사용해 쓰레드의 작업을 중지시켰다가 재개하거나 종료되도록 함
volatile boolean suspended = false;
volatile boolean stopped = false;
Thread th;
// 생성자, 생성자를 통해 이름을 가진 쓰레드를 생성함
Thread18_1(String name) {
th = new Thread(this,name); // Thread(Runnable r, String name)
}
@Override
public void run() {
String name = th.getName();
while(!stopped) {
// suspend가 false면 if문 실행, true면 else문 실행
if(!suspended) {
System.out.println(name);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println(name + " - interrupted");
}
} else {
Thread.yield(); // suspended값이 true면, 의미없는 무한반복으로 낭비, 다른 쓰레드에 실행시간을 양보
}
}
System.out.println(Thread.currentThread().getName() + " - stopped");
}
public void start() { th.start(); }
public void suspend() {
suspended = true;
th.interrupt(); // 25행에 의해 쓰레드가 sleep상태일 때, interrupt()를 호출하면 InterruptedException 발생
System.out.println(th.getName() + " - interrupt() by suspend()");
}
public void stop() {
stopped = true;
th.interrupt(); // 25행에 의해 쓰레드가 sleep상태일 때, interrupt()를 호출하면 InterruptedException 발생
System.out.println(th.getName() + " - interrupt() by stop()");
}
public void resume() { suspended = false; }
}
public class ThreadEx18 {
public static void main(String[] args) {
Thread18_1 th1 = new Thread18_1("*");
Thread18_1 th2 = new Thread18_1("**");
Thread18_1 th3 = new Thread18_1("***");
// 쓰레드 시작
th1.start();
th2.start();
th3.start();
try {
Thread.sleep(2000);
th1.suspend(); // th1쓰레드 잠시중단
Thread.sleep(2000);
th2.suspend();
Thread.sleep(3000);
th1.resume(); // th1쓰레드 재실행
Thread.sleep(3000);
th1.stop(); // th1쓰레드 종료
th2.stop(); // th2쓰레드 종료
Thread.sleep(2000);
th3.stop(); // th3쓰레드 종료
} catch(InterruptedException e) {}
}
}
|
cs |
29~31행에 else문을 추가하면서, suspended변수가 true일 경우 의미없이 무한반복하는 상태에서
yield()를 호출해, 무한반복하지 않고 다른 쓰레드에 양보하게 하면서 효율적으로 변경
39,45행에 interrupt()를 추가해 sleep()에서 InterruptedException이 발생하여 즉시 일시정지 상태에서 벗어나게 해 응답성을 향상시킴
join()
- 쓰레드 자신이 하던 작업을 잠시 멈추고 다른 쓰레드가 지정된 시간동안 작업을 수행하도록 함
- sleep()처럼 interrupt()에 의해 대기상테에서 벗어날 수 있음
- 호출되는 부분을 try-catch문으로 예외처리해야 함
- sleep()은 현재 쓰레드에 대해 동작, join()은 특정 쓰레드에 대해 동작
|
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
|
package thread;
class ThreadEx20_1 extends Thread {
final static int MAX_MEMORY = 1000; // 상수
int usedMemory = 0;
public void run() {
while(true) {
try {
Thread.sleep(10*1000); // 10초
} catch(InterruptedException e) {
System.out.println("Awaken by interrupt().");
}
gc();
System.out.println("Garbage Collected. Free Memory : " + freeMemory());
}
}
public void gc() {
usedMemory -= 300;
if(usedMemory<0) usedMemory = 0;
}
public int totalMemory() { return MAX_MEMORY; } // 상수값 반환
public int freeMemory() { return MAX_MEMORY - usedMemory; } // 상수-변수값 반환
}
public class ThreadEx20 {
public static void main(String[] args) {
ThreadEx20_1 gc = new ThreadEx20_1();
gc.setDaemon(true); // 데몬쓰레드 선언
gc.start();
int requiredMemory = 0;
for(int i=0; i<20; i++) {
requiredMemory = (int)(Math.random() * 10) * 20;
//
if(gc.freeMemory() < requiredMemory || gc.freeMemory() < gc.totalMemory()*0.4)
gc.interrupt(); // 10행에 의해 sleep상태인 쓰레드를 깨움
try {
gc.join(100);
} catch(InterruptedException e) {}
gc.usedMemory += requiredMemory; // 37행에 의해 생성되는 requiredMemory를 usedMemory에 합
System.out.println("usedMemory:"+gc.usedMemory);
}
}
}
|
cs |
'아카이브 > 자바의 정석' 카테고리의 다른 글
| 자바의 정석 16장 네트워킹 (0) | 2021.12.24 |
|---|---|
| 자바의 정석 15장 입출력 (0) | 2021.12.23 |
| 13장 쓰레드 20210104 (0) | 2021.01.04 |
| 13장 Thread 20201120 (0) | 2020.11.20 |
| 13장 Thread 20201118 (0) | 2020.11.18 |