멀티스레딩은 CPU 활용을 극대화하기 위해 프로그램의 두 개 이상의 부분을 동시에 실행하는 Java 기능입니다. 각각의 부분은 스레드(thread)라고 불리는 프로세스 내의 경량 프로세스가 됩니다.
스레드는 두 가지 방법으로 생성할 수 있습니다.
java.lang.Thread
클래스를 상속받아 클래스를 생성할 수 있습니다. Thread 클래스를 상속 받으면 run() 메서드를 재정의 할 수 있는데, run() 메서드의 내용이 스레드로 동작하게 됩니다. Thread 클래스를 상속받은 객체를 생성후, start() 메서드를 호출하여 스레드를 실행시킬 수 있습니다. start() 메서드는 Thread 객체 내부의 run() 메서드를 호출합니다.
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
java.lang.Runnable
인터페이스를 구현하는 클래스를 생성한 후 run() 메서드를 재정의 합니다. 이후 Thread 개체를 인스턴스화하고 이 개체에서 start() 메서드를 호출합니다.
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
출처