[JAVA] 9. 멀티 스레드(작업중)

H2Soft·2023년 7월 31일

JAVA

목록 보기
9/10

Runable 구현

public class PrintRunable implements Runnable {
	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.println("띵");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

Thread 상속

/*################################### 
Thread 상속 구현 
###################################*/
public class PrintThread extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.println("띵");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

스레드 우선 순위

내용

소스

데몬스레드

스레드 상태

  • NEW: 스레드 생성하고 start() 호출되지 않은 상태
  • RUNABLE:
  • BLOCKED,WATING : 일시정지
  • TIMED_WAITING : 일시정지(시간지정)
  • TERMINATED : 스레드 작업종료 상태

스레드 제어

https://docs.oracle.com/javase/8/docs/api/

sleep

  • static void sleep(long millis)
  • static void sleep(long millis, int nanos)
void delay(long milis){
	try{
    	Thread.sleep(milis);
    }catch(InterruptedException){
    }
}

interrupt

  • void interrupt()
  • static boolean interrupted()
  • boolean isInterrupted()

stop, suspend, resume

Deprecated. 필드변수로 처리 함수 만들어야함.

/* 
 * 스레드 Deprecated 된 suspended() 일시정지 , stop() 정지 , resume() 재실행 하는 함수 구현
 */
public class ThreadDeprecated implements Runnable {
	volatile boolean suspended = false;
	volatile boolean stoped = false;
	Thread th;
	
	public ThreadDeprecated() {}
	
	public ThreadDeprecated(String name) {		
		th = new Thread(this,name);
	}
	
	void start() {
		th.start();
	}
	void stop() {
		this.stoped = true;
	}
	void suspend() {
		this.suspended = true;
	}
	void resume() {
		this.suspended = false;
	}
	
	@Override
	public void run() {
		while (!stoped) {
			if(!suspended) {
				System.out.println(Thread.currentThread().getName());
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {}
			} else {
				Thread.yield();
			}
		}
	}
}

join

  • void join()
  • void join(long millis)
  • void join(long millis, int nanos)

yield

  • static void yield()

스레드 동기화

/* 쓰레드 동기화 */
	//메소드 동기화
	public synchronized void setMemory1(int memory) {
		this.memory = memory;
		
		try {
			Thread.sleep(2000); //2초간 일시 정지
		} catch (InterruptedException e) {}
		
		System.out.println(Thread.currentThread().getName()+":"+this.memory);
	}
	//블럭 동기화
	public void setMemory2(int memory) {
		synchronized (this) {
			this.memory = memory;
			try {
				Thread.sleep(2000); //2초간 일시 정지
			} catch (InterruptedException e) {}
			System.out.println(Thread.currentThread().getName()+":"+this.memory);
		}
	}

notify(), wait() 동기화로 인해 다른 스레드가 특정 메소드에 수행을 못하는걸 처리 하기 위해

profile
프로그램밍 정보 모음

0개의 댓글