
자바 스레드는 일반 스레드와 별반 차이가 없으며 자바 가상 기계(JVM)이 운영체제 역할을 한다.
class TimerThread extends Thread{
@Override
public void run(){ // thread 클래스의 run() 오버라이딩
......
}
}
TimerThread th = new TimerThread(); // 스레드 객체 생성
th.start();
// Java 스레드 예시 코드
class TimerThread extends Thread{
int n = 0;
@Overide
public void run(){
whlie(true){
System.out.println(n);
n++;
try{
sleep(1000);
}
catch(InterruptedException e){
return;
}
}
}
}
public class TestThread{
public static void main(String[] args){
TimerThread th = new TimerThread();
th.start();
}
}
// ** 실행 결과 **
// 0
// 1
// 2
// 3
// 4
// .
// .
// .
interface Runnable{
public void run();
}
class TimerRunnable implements Runnable{
@Override
public void run(){ // Runnable 인터페이스의 run() 메소드 오버라이딩
..........
}
}
Thread th = new Thread(new TimerRunnable()); // 스레드 객체 생성
th.start();
멀티스레드 프로그램이 실행될 때, 다수의 스레드가 공유 데이터를 동시에 접근하는 경우가 발생하는데 여러 스레드에 의해 공유 데이터의 값이 비정상적으로 유지되지 않도록 스레드의 실행을 제어하는 기술
코드 블록을 동기화가 설정된 임계 영역으로 지정하는 방법이 있으며, 메소드를 임계 영역으로 지정하는 방법과 임의의 코드 블록만 지정하는 방법이 있다.
// 1. 메소드를 임계 영역으로 지정하는 방법
sychronized void print(String text){
...
for(int i = 0; i < text.length(); i++){
System.out.println(text.charAt(i));
}
}
// 2. 임의의 코드 블록만 지정하는 방법
void execute(String text){
...
synchronized(this){ // 동기화 코드 블록
...
for(int i = 0; i < text.length(); i++){
System.out.println(text.charAt(i));
}
}
}