Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

Thread 본문

Java/다양한 기능

Thread

Seung__ 2021. 11. 1. 22:35

1. Thread???


  • process(실행중인 프로그램) : 프로그램이 실행되면 os로 부터 메모리를 할당받아 프로세스 상태가 됨.
    • process(프로그램이 메모리에 올라간 상태)
  • thread : 하나의 프로세스는 하나 이상의 thread를 가지게 되고, 실제 작업을 수행하는 단위는 thread
    • 프로그램이 돌아가려면 cpu를 점유해야 함.
    • CPU를 점유하는 단위가 thread

 

2. multi-threading


  • 여러 thread가 동시에 수행되는 프로그래밍. 여러 작업이 동시에 실행되는 효과
  • thread는 각각 자신만의 작업 공간을 가짐(context)
  • 각 thread사이에서 공유하는 자원이 있을 수 있음(자바는 static instance)
  • 여러 thread가 자원을 공유하여 작업이 수행되는 경우 서로 자원을 차지하려는 race condition이 발생할 수 있음.
  • 이렇게 여러 thread가 공유하는 자원 중 경쟁이 발생하는 부분을 critical section이라고 함.
  • critical section에 대한 동기화(일종의 순차적 수행, 동시에 사용하지 않도록 lock)를 구현하지 않으면 오류가 발생할 수 있음.

 

 

3. Thread만들기

  • Thread생성 방벙
    • Thread 상속
    • Runnable 인터페이스 구현 : run()구현 필요
  • Thread가 시작되면 thread의 run()메서드가 실행됨.
  • Thread상속
class MyThread extends Thread{

    public void run(){
        int i;
        for (i=1; i<=200; i++){
            System.out.print(i+"\t");
        }
    }
}

public class ThreadTest {

    public static void main(String[] args) {

        System.out.println(Thread.currentThread() + "start");
        MyThread th1 = new MyThread();
        MyThread th2 = new MyThread();

        th1.start();
        th2.start();
        System.out.println(Thread.currentThread() + "end");

    }
}
  • Runnable 구현
    • 클래스가 이미 다른 클래스를 상속받은 경우 사용
    • Runnable를 실행하기 위해서는 Thread에 runnable을 넣어주면 됨.
class MyThread implements Runnable{

    public void run(){
        int i;
        for (i=1; i<=200; i++){
            System.out.print(i+"\t");
        }
    }
}

public class ThreadTest {

    public static void main(String[] args) {

        System.out.println(Thread.currentThread() + "start");
        MyThread runnable = new MyThread();

        Thread th1 = new Thread(runnable);
        System.out.println(Thread.currentThread() + "end");

    }
}
  • Runnable 익명클래스
public class ThreadTest {

    public static void main(String[] args) {

        System.out.println(Thread.currentThread() + "start");
        MyThread runnable = new MyThread();

        Thread th1 = new Thread(runnable);
        System.out.println(Thread.currentThread() + "end");

        //익명클래스
       Runnable run = new Runnable() {
            @Override
            public void run() {
                int i;
                for (i=1; i<=200; i++){
                    System.out.print(i+"\t");
                }
            }
        };

    }
}

 

 

4. Thread Status


  • join()
    • thread1이 thread2의 결과가 필요해서 thread2에  join을 걸면 thread1이 not runnable상태로 빠짐.
    • thead2가 끝나야 thread1이 runnable상태로 바뀜.

 

 

 

5. GitHub : 211001 Thread


 

GitHub - bsh6463/various_functions

Contribute to bsh6463/various_functions development by creating an account on GitHub.

github.com

 

Comments