[Java 8] Java Concurrent

홍정완·2022년 6월 19일
0

Java

목록 보기
10/25
post-thumbnail

Concurrent SW


  • 동시에 여러 작업을 할 수 있는 SW

  • ex) 녹화를 하면서 인텔리 J로 코딩을 하고 워드에 적어둔 문서를 보거나 수정할 수 있다.


Java에서 지원하는 Concurrent Programming

  • 멀티프로세싱 (ProcessBuilder)

  • 멀티쓰레드


Java 멀티쓰레드 Programming

  • Thread / Runnable



Thread 상속


	public static void main(String[] args) {
    
        HelloThread helloThread = new HelloThread();
        helloThread.start();
        System.out.println("hello : " + Thread.currentThread().getName());
    }

    static class HelloThread extends Thread {
        @Override
        public void run() {
            System.out.println("world : " + Thread.currentThread().getName());
        }
    }



Runnable 구현 or 람다


Thread thread = new Thread(() -> System.out.println("world : " + Thread.currentThread().getName()));
thread.start();
System.out.println("hello : " + Thread.currentThread().getName());



Thread 주요 기능


  • 현재 쓰레드 멈춰두기 (sleep)

    • 다른 쓰레드가 처리할 수 있도록 기회를 주지만 그렇다고 락을 놔주진 않는다.
    • (잘못하면 데드락)
    public static void main(String[] args) {

        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("world : " + Thread.currentThread().getName());
        });

        thread.start();
        System.out.println("hello : " + Thread.currentThread().getName());

    }



  • 다른 쓰레드 깨우기 (interupt)

    • 다른 쓰레드를 깨워서 interruptedExeption을 발생시킨다.
    • 그 에러가 발생했을 때 할 일은 코딩하기 나름.
    • 종료 시킬 수도 있고 계속하던 일할 수도 있다.
	public static void main(String[] args) throws InterruptedException {
    
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("Tread : " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("interrupted!");
                }
            }
        });
        
        thread.start();
        System.out.println("hello : " + Thread.currentThread().getName());

        Thread.sleep(3000);
        thread.interrupt();
    }



  • 다른 쓰레드 기다리기 (join)

    • 다른 쓰레드가 끝날 때까지 기다린다.
	public static void main(String[] args) throws InterruptedException {
    
        Thread thread = new Thread(() -> {
            System.out.println("Tread : " + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        });
        thread.start();

        System.out.println("hello : " + Thread.currentThread().getName());
        thread.join(); // 해당 쓰레드를 기다린 후
        System.out.println(thread + " is finished");
    }
profile
습관이 전부다.

0개의 댓글