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 상속 구현
###################################*/
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 : 스레드 작업종료 상태
void delay(long milis){
try{
Thread.sleep(milis);
}catch(InterruptedException){
}
}
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();
}
}
}
}
/* 쓰레드 동기화 */
//메소드 동기화
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() 동기화로 인해 다른 스레드가 특정 메소드에 수행을 못하는걸 처리 하기 위해