프로세스는 프로그램을 수행하는데 필요한 데이터와 메모리 등의 자원 그리고 쓰레드로 구성되어 있으며 프로세스의 자원을 이용해서 실제로 작업을 수행하는 것이 바로 쓰레드이다. 하나의 프로세스 내에서 여러 개의 스레드가 동시에 실행될 수 있다.
쓰레드를 구현하는 방법은 Thread클래스를 상속받는 방법과 Runnable 인터페이스를 구현하는 방법이 있다.
run()을 오버라이딩
//스레드(Thread) : 프로세스내에서 동시에 여러 작업을 수행할 수 있다.
//할당받은 자원을 이용해서 실제 작업을 수행한다.
//다중스레드(Multi Thread) : 스레드가 2개 이상 존재하는 경우를 말하며 프로그램의 성능을 향상시킬 수 있다.
class MyThread extends Thread{
//Thread 클래스의 run 메소드 Override
//스레드가 실행됐을 때 수행되는 작업을 run메서드에 정의한다.
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(getName() + "value = " + i);//getName - 스레드 이름 : [Thread - 번호]
}
}
}
public class _01_MyThread {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start();//스레드 생성 => start 메서드내에서 run 메서드 호출
t2.start();
}
}
Runnable 인터페이스는 오로지 run()만 정의되어 있는 간단한 인터페이스다. ( run()을 구현)
class MyRunnable implements Runnable {// Runnable 구현
public void run() {
for(int i = 0; i < 5; i++) {
// Thread.currentThread() => 현재 실행중인 스레드의 주소를 리턴
//클래스명.static메서드 => Thread의 멤버를 가져다 쓰고 싶은 경우
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);//실습을 위해 1초씩 느리게 만든다.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class _02_MyRunnable {
public static void main(String[] args) {
MyRunnable r1 = new MyRunnable();
Thread t1 = new Thread(r1);
MyRunnable r2 = new MyRunnable();
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
MultiThread
class PrintCharThread extends Thread{
PrintCharThread(char _ch, int _count){
ch = _ch;
count = _count;
}
@Override
public void run() {
//스레드가 처리 할 명령
for(int i = 0; i < count; i++) {
System.out.print(ch);
}
System.out.println("\nRun Time" + (System.currentTimeMillis() - _05_MultiThread.startTime));
}
private char ch;
private int count;
}
public class _05_MultiThread {
static long startTime;//정적멤버
public static void main(String[] args) {
startTime = System.currentTimeMillis();
PrintCharThread t1 = new PrintCharThread('*', 800);
PrintCharThread t2 = new PrintCharThread('@', 800);
t1.start();
t2.start();
}
}'JavaStudy' 카테고리의 다른 글
| [Java] Lambda expression(람다식) (0) | 2023.12.12 |
|---|---|
| [Java] synchronized (0) | 2023.12.12 |
| [Java] Anonymous(익명클래스) (0) | 2023.12.11 |
| [Java] TreeMap (1) | 2023.12.08 |
| [Java] HashMap과 Hashtable (0) | 2023.12.06 |