Web Developer/JAVA II
11. Thread 예제 및 연습문제
sayitditto
2023. 1. 22. 14:22
ThreadTest
Thread 만들기 1 -> 상속 받아서 사용
// 한 가지 단점: 자바는 단일 상속이으며 thread를 상속 받으면 다른 클래스를 함께 상속 받을 수 없음
public static void main(String[] args) throws InterruptedException {
ThreadExtends te1 = new ThreadExtends("★");
ThreadExtends te2 = new ThreadExtends("☆");
Single thread : 순차적으로 수행
te1.run();
te2.run();
Multi thread : 각각의 쓰레드가 동시에 수행 (start메소드 써야함)
속도가 빨라서 싱글쓰레드로 보임 (sleep을 추가해야만 함)
te1.start();
te2.start();
Thread 만들기 2 -> Runnable 인터페이스 구현
// 장점: 다중 상속 가능
// 단점: 멀티 thread 를 위해 thread 객체를 객체에 담아서 사용한다.
ThreadImplements ti1 = new ThreadImplements("○");
ThreadImplements ti2 = new ThreadImplements("●");
// Single Thread 순차적 수행
// ti1.run();
// ti2.run();
Thread t1 = new Thread (ti1);
Thread t2 = new Thread (ti2);
// Multi Thread
t1.start();
t1.join(); // main thread가 t1 thread가 일을 다 할때 까지 기다린다.
t2.start();
t2.join();
System.out.println("메인 메소드 끝");
}
}
ThreadExtends
public class ThreadExtends extends Thread {
private String resource;
public ThreadExtends(String resource) {
this.resource = resource;
}
@Override
public void run() {
// 여기서 구현하는 내용이 쓰레드에서 수행됨
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(500); // 0.5초씩 쉬면서 찍는다.
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.resource);
}
}
}
ThreadImplements
public class ThreadImplements implements Runnable{
private String resource;
public ThreadImplements(String resource) {
this.resource = resource;
}
@Override
public void run() {
// 여기서 구현하는 내용이 쓰레드에서 수행됨
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(500); // 0.5초씩 쉬면서 찍는다.
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(resource);
}
}
}
ThreadQuiz - Runnable
동물원에 동물 3마리가 있다.
각 동물들은 1초에 한번씩 울음소리를 낸다.
항상 2마리의 동물이 먼저 울고 남은 한마리 동물이 나중에 운다.
각 동물은 5번씩만 울고 잠에 든다.
Test
public static void main(String[] args) throws InterruptedException {
thread_zoo animal1 = new thread_zoo("어흥");
thread_zoo animal2 = new thread_zoo("음메~");
thread_zoo animal3 = new thread_zoo("히잉");
Thread tiger = new Thread (animal1);
Thread cow = new Thread (animal2);
Thread horse = new Thread (animal3);
tiger.start();
cow.start();
tiger.join();
cow.join();
horse.start();
}
Zoo
public class thread_zoo implements Runnable {
private String cry;
public thread_zoo (String cry) {
this.cry = cry;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(cry);
}
}
}