System.out.println("Hello, World");

Thread를 extends하는 예제

예제

ThreadTest1

public class ThreadTest1 {
	public static void main(String[] args) {
		Print1to30Thread pt1 = new Print1to30Thread();
		pt1.start();
		PrintAtoZThread pt2 = new PrintAtoZThread();
		pt2.start();
		PrintAtoZLowThread pt3 = new PrintAtoZLowThread();
		pt3.start();
		//동시에 같이 일을 하게 되어서 랜덤으로 스레드가 실행된다.		
	}
}

PrintAtoZThread
//A에서 Z까지 출력하는 Thread
public class PrintAtoZThread extends Thread{
	public void run(){
		//Thread의 실행 코드가 들어온다.
		for(int i = 65; i<91; i++)
		{
			System.out.print((char)i);
		}
		System.out.println();
	}
}
PrintAtoZLowThread
public class PrintAtoZLowThread extends Thread{
	public void run(){
		for(int i=97; i<97+26; i++){
			System.out.print((char)i);
		}
		System.out.println();
	}
}
Print1to30Thread
public class Print1to30Thread extends Thread{
	public void run(){
		for(int i=0; i<31; i++){
			System.out.print(i);
		}System.out.println();
	}
}

<결과>


결과는 위와 같이 랜덤으로 출력된다. 그 이유는 메소드처럼 순서대로 실행되는게 아니라 Thread는 동시에 실행되므로 결과값들이 위와 같이 상이하게 나오게 된다.


-Runnable에서 Running으로 변화시켜주는건 프로그래머는 모르고 JVM이 처리한다.

-다른일을 처리하다가 다른쪽에서 Running상태가 되고 자신의 상태가 Runnable상태가 된후 다시 Running으로 되돌아간다면 아까 멈췄던 곳에서 다시 시작한다.


Thread.Sleep(int 밀리초)

특정 Thread가 Dead(완료)될때까지 실행중인 thread를 멈춘다.(실행중인 Thread를 밀리초동안 멈춘다.)

멈춘후 해당 Thread는 Blocked상태가 된다.


Thread객체.join()

특정 Thread가 Dead(완료)될때가지 실행중인 Thread를 멈춘다.(메소드 오버로딩 되있음)

Thread가 멈춰서 Blocked상태가 된다.


Thread를 implements하는 예제

ThreadTest
public class ThreadTest {
	public static void main(String[] args) {
		Print1to99Thread pt1  = new Print1to99Thread();
		Print100to900Thread pt2 = new Print100to900Thread();
		Thread t1 = new Thread(pt1);//Thread 객체를 생성해서 담아줘야 한다.
		Thread t2 = new Thread(pt2);//Thread 객체를 생성해서 담아줘야 한다.
		t1.start();		
		t2.start();
		System.out.println("메인종료");
		//모든 스레드가 Dead하면 끝난다.		
	}
}

Print100to900Thread
public class Print100to900Thread implements Runnable{
	public void run() {
		for(int i=100; i<=900; i=i+100){
			System.out.println(i);
		}	
		//메소드 수행이 끝나면 Dead한다.
	}
}
Print1to99Thread
public class Print1to99Thread implements Runnable{
	public void run() {
		for(int i=0; i<99; i=i+5){
			System.out.println(i);
		}		
		//메소드 수행이 끝나면 Dead한다.
	}
}

<결과>


Thread Sleep 예제 
ThreadSleepTest

public class GoThread extends Thread{
	public void run(){
		for(int i = 0; i<10; i++){
			System.out.println("GoThread: " +i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

ComeThread
public class ComeThread extends Thread{
	public void run(){
		for(int i=0; i<10; i++){
			System.out.println("Come Thread : " + i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}	
}

<결과>

1초마다 파일을 생성하면서 20초마다 파일을 긁어오는 Thread 예제  


ThreadTest
public class ThreadTest {
	public static void main(String[] args) {
		MakeFileThread t1 = new MakeFileThread();
		MoveFileThread t2 = new MoveFileThread();
		t1.start();		
		t2.start();
	}
}

MakeFileThread
public class MakeFileThread extends Thread{
	//매 1초에 하나의 파일을 생성한다. 1분동안 - FIle명 costa.1, costa.2, costa.3
	public void run(){
		for(int i=1; i<60; i++){
			//만약 디렉토리 파일이 없다면 생성해줘야 한다.
			//File dir = new File("D:\\temp");
			//if(!dir.exits)
			//dir.mkdir(); 디렉토리가 없으면 만들어라
			File file = new File("D:\\temp\\costa."+i);
			Boolean flag;
			try {
				flag = file.createNewFile();
				//파일 생성하기
				System.out.println("파일 생성 여부 : "+i+"번째"+flag);
			} catch (IOException e) {
				e.printStackTrace();
			}			
			try {
				//1초간 멈추기
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

MoveFileThread
public class MoveFileThread extends Thread {
	// makeThread에서 만든 파일을 다른 경로로 이동 = 매 20초당 한번씩- 1분동안 처리한다.
	public void run() {
		for (int i = 0; i < 3; i++) {
			//for(int i=0; i<3; i++){
			//원본파일이 있는 디렉토리 내의 파일 리스트 ㅂ루러오기
			//File newFilesDir = new File("D:\\temp");
			//String [] fileList = newsFilesDir.list();
			//파일 옮기기
			//for(String f : fileList){
			//if(file.isDirectory())//만약 디렉토리면 안옮기게따
			//continue;
			//File file =new File(newsWifle,f);
			//file.renameTo(new File("D:\\temp2");
			//Thread.sleep(20000); 20초동안 잔다.
			try {
				Thread.sleep(20000);//20초 쉬었다가 밑에 있는 거 실행한다.
			} catch (InterruptedException e) {
				e.printStackTrace();				
			}
			for (int j = 0;  j<60; j++) {
				//원본파일이 있는 디렉토리내의 파일 리스트 불러오기
				File origin = new File("D:\\temp\\costa." + j);
				File newfile = new File("D:\\temp2\\costa." + j);
				Boolean flag = origin.renameTo(newfile);
				System.out.println("파일 옮겨졌을까 : " + flag);
			}				
		}
	}
}




Thread를 join을 이용하는 예제 

SumThread

public class SumThread extends Thread{
	private int first;
	private int last;
	private int sum;
	public SumThread(int first, int last){
		this.first = first;
		this.last = last;		
	}
	public int getSum(){
		return sum;
	}	
	public void run(){
		//first에서 last까지 1씩 더하기
		//1+2+3+4+5+6+7+8+9+10
		for(int i = first; i<=last; i++){
			sum = sum+i;
		}
	}
}
ThreadTest
public class ThreadTest {
	public static void main(String[] args) {
		SumThread t1 = new SumThread(1, 10);		
		t1.start();		
		try {
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}//t1이 끝날때까지 블럭하겠다.
		int sum = t1.getSum();
		System.out.println("1부터 10까지의 총합 : " +sum);
		}
}

만약 ThreadTest에서 t1.join을 사용하지 않을 경우에는 t.start()가 SumThread의 getSum()보다 빨리 실행된다. 빨리 실행되는 이유는 main이 더 짧고 getSun()에서는 연산이 들어가있기 때문에 main이 더 빨리 실행되게 된다. 

또한 Thread.sleep()을 사용할수 있지만 멈춰있는 시간이 연산되는 시간보다 적을수 있기 때문에 join을 사용해야 한다. 

Posted by 김마농