Threadclass orRunnableinterface로 쉽게 생성가능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();
}
}
synchronized를 이용synchronizede.g. public synchronized void produce()
ㄱ. thread가 synchronized method실행시 해당 객체를 lock함
ㄴ. 하나의 thread만 lock을 할 수 있음 ⟹ 따라서 해당 메서드는 그 스레드만 작동 가능
ㄷ. method가 끝나면 lock은 해제됨
wait()스레드는 notify()ornotifyAll()메서드가 호출될 때까지 기다린다.
notify()ornotifyAll()notify() 대기 중인 스레드 중 하나를 활성상태로 전환notifyAll() 대기 중인 모든 스레드를 활성 상태로 전환*메서드
| Method | Meaning |
|---|---|
| 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. |