JAVA_Thread

0ne·2024년 6월 10일

java

목록 보기
2/11

정의

Separate Computation Process

  • multiple operation을 concurrently하게 할 수 있게 함

Parallel execution

  • multiple threads를 동시에

Single Sequential Flow

  • each thread는 코드를 선형적으로 처리함

Shared Resource

  • Thread는 고유의 메모리 공간을 가지지 않음
  • 대신 프로세스의 메모리와 자원을 공유함
    * 각 프로세스는 다른 프로세스와 메모리 공간을 공유하지 않음
    * 프로세스의 메모리 공간 : 코 데 힙 스
    * 스레드는 독립적인 스택을 가짐, 같은 코드, 데이터, 힙 영역을 공유함

특성

Lightweight

  • Thread간 전환 비용 << process간 전환 비용

easy to spawn

  • Threadclass orRunnableinterface로 쉽게 생성가능
    * Runnable 선호; 다른 클래스 상속 가능하므로

priority 존재

  • 1~10까지
  • 5가 디폴트

사용

multithreading

언제

  • parallel processing(프로세스 내) 향상
  • user반응성 증가
  • cpu의 idle 시간 활용
  • priority에 다른 작업 처리 가능

run()구현 -> start()로 스레드 생성 후 run실행

class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " is running: " + i);
            try {
                Thread.sleep(1000); // 1초 대기
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class RunnableExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());

        // 스레드를 시작
        thread1.start();
        thread2.start();
    }
}

synchronization

  • multithreading은 asynchronous처리를 하게 하는데 필요할 때 synchronicity하게 처리 할 수 있어야 한다.
  • synchronized를 이용

언제

  • thread interference 방지
  • consistency 문제 방지
  • data corruption 방지

작동 방식

synchronized

e.g. public synchronized void produce()
ㄱ. thread가 synchronized method실행시 해당 객체를 lock함
ㄴ. 하나의 thread만 lock을 할 수 있음 ⟹ 따라서 해당 메서드는 그 스레드만 작동 가능
ㄷ. method가 끝나면 lock은 해제됨

wait()

스레드는 notify()ornotifyAll()메서드가 호출될 때까지 기다린다.

notify()ornotifyAll()

  • notify() 대기 중인 스레드 중 하나를 활성상태로 전환
  • notifyAll() 대기 중인 모든 스레드를 활성 상태로 전환

*메서드

MethodMeaning
Thread currentThread()returns a reference to the current thread
Void sleep(long msec)causes the current thread to wait for msec milliseconds
String getName()returns the name of the thread.
Int getPriority()returns the priority of the thread
Boolean isAlive()returns true if this thread has been started and has not yet died. Otherwise, returns false.
Void join()causes the caller to wait until this thread dies.
Void run()comprises the body of the thread. This method is overridden by subclasses.
Void setName(String s)sets the name of this thread to s.
Void setPriority(int p)sets the priority of this thread to p.
profile
@Hanyang univ(seoul). CSE

0개의 댓글