(자바교육/JAVA교육)자바에서 스레드(Thread) 만들기(자바학원/자바/JAVA/자바강좌/자바동영상/자바강의/JAVA강의/JAVA동영상)
1. Thread 클래스
하나의 쓰레드를 생성 및 관리
public class Thread extends Object implements Runnable
Thread()Allocates a new Thread object. |
Thread(Runnable target, String name)Allocates a new Thread object. |
Thread(ThreadGroup group, Runnable target)Allocates a new Thread object. |
Thread(ThreadGroup group, Runnable target, String name)Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group. |
Thread(ThreadGroup group, Runnable target, String name, long stackSize)Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size. |
Thread(ThreadGroup group, String name)Allocates a new Thread object. |
메쏘드
start() : 새로운 스레드를 생성하고 이 스레드에서 정의된 run() 메소드를 자동으로 실행 한다.
run() : 새롭게 생성된 스레드가 실행할 메소드로 수행되어야 할 새로운 스레드의 코드와 함께 반드시 오버라이드 되어야 한다.새롭게 생성된 스레드의 main 메소드와 같다고 볼 수 있으며 새롭게 생성된 스레드의 일반적인 프로그램이 run()메소드로 부터 수행이 시작된다.
Thread.currentThread() : 현재 작업중인 스레드 객체를 얻는다.
자바에서 스레드는 Thread 클래스를 상속받거나 Runnable 인터페이스를 구현해서 만든다.
상속받아 만드는 것보다 Runnable 인터페아스를 구현하는 것이 나중을 위해 좋다. (자바는 단일상속)
2. Runable 인터페이스
스레드를 만들기 위한 방법 run이라는 인수가 없는 메서드를 정의해야 한다.
자바8 부터 FunctionalInterface로 선언됨
자바는 단일 상속만 가능 하다.
상위 클래스를 Thread로 할 수 없을 경우 사용.
@FunctionalInterface
public interface Runnable{
void run();
}
3. 실습
// Runnable 인터페이스를 이용한 스레드 생성
class HelloThread implements Runnable {
@Override
public void run() {
System.out.println("Hello~ Thread...");
}
}
public class ThreadTest1 {
public static void main(String[] args) {
HelloThread helloThread = new HelloThread();
new Thread(helloThread).start();
//람다식이용, Runnable은 함수형 인터페이스(추상메소드가 딸랑 하나)
new Thread( () -> System.out.println("Hello~ Thread2...")).start();
}
}
4. 실습
package javatest;
// Thread 클래스를 상속받아 스레드 생성
class HelloThread extends Thread {
@Override
public void run() {
System.out.println("Hello~ Thread...");
}
}
public class ThreadTest1 {
public static void main(String[] args) {
HelloThread helloThread = new HelloThread();
helloThread.start();
}
}
#자바스레드, #자바쓰레드, #자바Thread, #자바쓰레드예제, #스레드, #자바, #JAVA, #자바동영상, #자바강의, #자바교육, #자바강좌, #자바동영상강의, #추천자바강의, #추천자바강좌, #JAVA동영상, #JAVA강의, #JAVA강좌, #JAVA교육, #JAVA, #추천JAVA강의, #추천JAVA교육, #추천JAVA강좌, #자바소스, #자바온라인교육, #자바온라인강의
댓글 없음:
댓글 쓰기