자바 스레드
자바 스레드
스레드를 사용하면 동시에 여러 작업을 수행하여 프로그램이 보다 효율적으로 작동할 수 있습니다.
스레드는 메인 프로그램을 중단하지 않고 백그라운드에서 복잡한 작업을 수행하는 데 사용할 수 있습니다.
스레드 생성
쓰레드를 생성하는 방법은 2가지가 있습니다.
클래스를 확장하고 해당 메서드 Thread
를 재정 의하여 만들 수 있습니다 .run()
확장 구문
public class Main extends Thread { public void run() { System.out.println("This code is running in a thread");
}}
스레드를 만드는 또 다른 방법은 Runnable
인터페이스를 구현하는 것입니다.
구문 구현
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}
스레드 실행
클래스가 클래스를 확장하는 경우 Thread
클래스의 인스턴스를 만들고 해당 start()
메서드를 호출하여 스레드를 실행할 수 있습니다.
확장 예제
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
클래스가 인터페이스를 구현하는 경우 클래스 Runnable
의 인스턴스를 객체의 생성자에 전달한 다음 스레드의 메서드 Thread
를 호출하여 스레드를
실행할 수 있습니다.start()
구현 예
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
스레드 "확장"과 "구현"의 차이점
주요 차이점은 클래스가 Thread 클래스를 확장할 때 다른 클래스를 확장할 수 없지만 Runnable 인터페이스를 구현하면 class 와 같은 다른 클래스에서도 확장할 수 있다는 것입니다 MyClass extends OtherClass implements Runnable
.
동시성 문제
스레드는 프로그램의 다른 부분과 동시에 실행되기 때문에 코드가 실행되는 순서를 알 수 있는 방법이 없습니다. 쓰레드와 메인 프로그램이 같은 변수를 읽고 쓸 때 값은 예측할 수 없습니다. 이로 인해 발생하는 문제를 동시성 문제라고 합니다.
예시
변수 금액 의 값을 예측할 수 없는 코드 예제:
public class Main extends Thread { public static int amount = 0; public static void main(String[] args) { Main thread = new Main(); thread.start(); System.out.println(amount); amount++; System.out.println(amount);
}public void run() { amount++;
}}
동시성 문제를 방지하려면 스레드 간에 가능한 한 적은 수의 속성을 공유하는 것이 가장 좋습니다. 속성을 공유해야 하는 경우 한 가지 가능한 솔루션은 isAlive()
스레드가 변경할 수 있는 속성을 사용하기 전에 스레드의 실행이 완료되었는지 여부를 확인하기 위해 스레드의 메서드를 사용하는 것입니다.
예시
isAlive()
동시성 문제를 방지하기 위해 사용 :
public class Main extends Thread { public static int amount = 0; public static void main(String[] args) { Main thread = new Main(); thread.start(); // Wait for the thread to finish while(thread.isAlive()) { System.out.println("Waiting...");
}// Update amount and print its value System.out.println("Main: " + amount); amount++; System.out.println("Main: " + amount);
}public void run() { amount++;
}}