1교시
---Thread---
--프로세스--
컴퓨터에 저장되어있는 실행하는 순간 메모리에 올라가고 동작을 하게 되는데 이 상태를 프로세스라고한다.
--스레드--
1. 프로세스가 여러개의 작업을 수행할수있게 해주는것
2. 프로세스 내부에 존재하면서 실행의 흐름을 나타낸다.
---프로세스 실행방식---
1. 시간 분할 방식 : 모든 프로세스에 동일한 시간을 할당하고 골고로 실행되는방식
2. 선점형 방식 : 각각의 프로세스에게 우선 순위를 부여하고 높은 순으로 실행되는 방식
---JVM이 스레드 처리시 하는일---
1. 스레드 스케줄링
2. 스레드가 몇개 존재하는지
3. 스레드가 실행되는 프로그램 코드의 메모리 위치가 어디인지,
현재 스레드의 상태는 무엇인지, 스레드의 우선순위는 몇인지
---개발자가 스레드 처리시 하는일---
1.자바 스레드로 작동할 작업이 무엇인지 코드로 작성
2.스레드 코드가 실행할수 있도록 JVM에 요청
---스레드를 생성하는방법---
1. Thred 클래스를 상속받는다.(Thread)
2. run을 오버라이딩 받는다.
---run---
1.run() 메서드로 직접 호출을 해버리게 되면 독립적으로 수행하지못한다. 일반 메서드처럼 순차적으로 실행이 된다.
2.독립적으로 사용하고 싶다면, start() 메서드를 사용해야한다.
---Thread 주요 메서드---
static Thread currentThread() //현재 수행되는 스레드 객체를 반환
String getname() //스레드의 이름을 반환
void set name(String name) //스레드의 이름을 지정
int getpriority() //스레드의 우선순위를 반환
void setpriority(int priority) //스레드의 우선순위 지정(디폴트 5)
void start() // 스레드를 시작
String getState() //현재 스레드의 상태를 반환(RUNNABLE 사용가능의미)
2교시
---스레드의 상태---
1. 스레드는 생성하고 실행, 종료되기까지 다양한 상태를 가진다.
2. 각 스레드의 상태는 스레드 클래스에 정의되어 있으며 Thread.State타입으로 알수있다.
3. 스레드의 상태에 따라 6개의 타입으로 분류하고있다.
4.스레드가 처음 생성되면 NEW상태가 된다. 생성이루에 start() 메서드를 실행하면 스레드는 RUNNABLE상태로 변하고
시작이후에 스레드가 종료되면 TERMINATRD상태가 된다.
5.스레드 WAIT 상태는 필요에 의해서 스레드를 잠시 멈춤 상태로 두는것.
스레드를 잠시 멈춤 상태로 만들때는 일정 시간을 지정하거나, 멈춤 상태의 락이 풀릴때까지 대기하도록 만들수있다.
---생성상태---
스레드 객체가 생성되었지만 start()로 호출되지않은 상태(상수 new)
---대기상태---
RUNNABLE 실행 대기 또는 실행 상태를 언제든지 갈수있는 상태(상수 RUNNABLE)
---일시정지---
(상수 WATING)다른 스레드가 종료될 때 까지 대기하는 상태
(상수 TIMED_WATING)주어진 시간동안 대기하는 상태
(상수 BLOCKED) 락이 풀릴 때까지 대기하는 상태
(상수 TERMINATED) 수행을 종료한 상태
---상태변화 메서드---
스레드의 상태를 변환시키는 다양한 메서드가 있다.
static void sleep(Long millis) millisecond에 지정된 시간만큼 대기
void join() : 현재 스레드는 join() 메서드를 호출한 스레드가 종료할 때가지 대기
static void yield : 수행중인 스레드 중 우전순위가 같은 스레드에게 제어권을 넘긴다.
---sleep()---
sleep()메서드 사용시 try.catch 메서드를 무조건 써줘야한다. 중간에 방해받을수 있기 때문에 그렇다.
---wait()/notify()---
여러개의 스레드가 동시에 작동하다보면, 하나의 스레드가 완료 되어야 다음 스레드가 동작할수있는 경우가 있다.
ex)한쪽에는 물건을 나르고, 한쪽에서는 물건을 쌓는 스레드가 있다고 가정해보자
만약 쌓을 물건이 없다면 나르는 스레드는 할일이 없어진다.
이때 물건의 나르는 스레드를 잠시 중단시키고, 물건이 오면 다시 나르도록 할 수있다.
wait()메서드는 스레드를 대기시키고, notify()메서드는 대기중인 스레드를 다시 동작시킬때 사용한다.
3교시
---Thoread예시1---
package Ex3_Thread;
public class SleepThread extends Thread {
@Override
public void run() {
System.out.println("카운트다운 5초");
for(int i=5; i>0; i--) {
System.out.println(i);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("종료");
}
}
package Ex3_Thread;
public class SleepMain {
public static void main(String[] args) {
SleepThread st = new SleepThread();
st.start();
}
}
---Thoread예시2---
public class Storage1 {
//재고
private int stackCount = 10;
//재고추가
public synchronized void addStack(int stackCount) {
this.stackCount += stackCount;
if(this.stackCount>=10) {
System.out.println("===스레드 꺠우기===");
notify();
}
}
public synchronized void popStack(int leaveCount) {
try {
if(leaveCount>this.stackCount) {
this.stackCount = 0;
}else {
this.stackCount-=leaveCount;
}
if(this.stackCount == 0) {
System.out.println("==짐 없음 대기==");
wait();
System.out.println("==짐 없음 대기완료==");
}
} catch (Exception e) {
// TODO: handle exception
}
}
public int getStackCount() {
return this.stackCount;
}
}
package Ex3_Thread;
class Storage {
private int stackCount;
public int getStackCount() {
return stackCount;
}
public void addStack(int amount) {
stackCount += amount;
}
public void popStack(int amount) {
stackCount -= amount;
}
}
class AddStackThread extends Thread {
private Storage1 storage;
public AddStackThread(Storage1 storage) {
this.storage = storage;
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
if (this.storage.getStackCount() == 0) {
System.out.println("짐 10개 추가");
this.storage.addStack(10);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class PopStackThread extends Thread {
private Storage1 storage;
public PopStackThread(Storage1 storage) {
this.storage = storage;
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
System.out.println("짐 5개 나르기");
this.storage.popStack(5);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ThreadWaitExample {
public static void main(String[] args) {
Storage1 s = new Storage1();
AddStackThread add = new AddStackThread(s);
PopStackThread pop = new PopStackThread(s);
add.start();
pop.start();
}
}
---데몬스레드---
1. 데몬스레드는 다른 일반 스레드의 작업을 돕는 보조적인 역할을 수행하는 스레드이다.
2. 함께 구동중인 일반 스레드가 종료되면 데몬스레드도 함께 종료된다.
3. ex)문서를 작성하는 도중 3초 간격으로 자동 세이브 하는것.
---데몬스레드 예제1---
public class DaemonTest {
public static void main(String[] args) {
Thread daemonThread = new Thread(new MyDaemonRunnable());
daemonThread.setDaemon(true); // 스레드를 데몬 스레드로 설정
daemonThread.start();
for(int i =1; i<=15; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println("메인스레드 종료");
}
}
class MyDaemonRunnable implements Runnable { // Runnable 인터페이스를 구현하도록 수정
@Override
public void run() {
try {
for (int i = 0; i <= 15; i++) {
System.out.println("저장되었습니다.");
Thread.sleep(3000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
'(학) (공) (자)' 카테고리의 다른 글
자바 기초 커리큘럼 (1) | 2024.04.04 |
---|---|
01.23 (17일차) (0) | 2024.01.23 |
01.18(14일차) (0) | 2024.01.18 |
01.16(12일차) (0) | 2024.01.16 |
01.15(11일차) (1) | 2024.01.15 |