자바15일차

달달한스위츠·2024년 2월 22일

자바배우기

목록 보기
15/43

오늘의 코드
쓰레드 부터

package edu.java.thread02;

// 자바는 다중 상속을 허용하지 않기 때문에
// 다른 클래스를 이미 상속받고 있는 경우에는 Thread 클래스를 상속받을 수 없음
// Runnable 인터페이스를 구현하여 Thread를 생성할 수 있는 방법을 제공

// 자바에서 쓰레드를 생성하고 사용하는 방법2
// 1. Runnable 인터페이스를 구현하는 클래스 정의(implements Runnable)
// 2. 정의한 클래스에서 run() 메소드를 override
// -> 쓰레드가 해야 할 기능 구현
// 3. 정의한 클래스(Runnable 구현 클래스)의 인스턴스 생성
// 4. Runnable 인스턴스를 매개변수로 해서 Thread 인스턴스를 생성
// 5. Thread 인스턴스에서 start() 메소드를 호출 -> run() 자동 호출

class MyRunnable1 implements Runnable {
	private String msg;

	public MyRunnable1(String msg) {
		this.msg = msg;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(i + " : " + msg);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

} // end MyRunnable1

class MyRunnable2 implements Runnable {
	private String msg;

	public MyRunnable2(String msg) {
		this.msg = msg;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(i + " : " + msg);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

} // end MyRunnable2

public class ThreadMain02 {

	public static void main(String[] args) {
		MyRunnable1 r1 = new MyRunnable1("r1");
		MyRunnable2 r2 = new MyRunnable2("r2");
		
		Thread th1 = new Thread(r1);
		Thread th2 = new Thread(r2);
		
		th1.start();
		
		try {
			// 해당 쓰레드가 종료될 때까지 다른 쓰레드가 기다림
			th1.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		th2.start();

	} // end main()

} // end TreadMain02
package edu.java.thread03;

class MyRunnable1 implements Runnable {

	private String msg;

	public MyRunnable1(String msg) {
		this.msg = msg;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(i + " : " + msg);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

} // end MyRunnable1

class MyRunnable2 implements Runnable {
	private String msg;

	public MyRunnable2(String msg) {
		this.msg = msg;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			System.out.println(i + " : " + msg);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

} // end MyRunnable2

public class ThreadMain03 {

	public static void main(String[] args) {
		// 1. 클래스 인스턴스를 생성하여 쓰레드 start()
		Thread th1 = new Thread(new MyRunnable1("클래스"));
		th1.start();

		// 2. 익명 클래스를 사용하여 쓰레드 start()
		Thread th2 = new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 100; i++) {
					System.out.println(i + " : 익명");
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}
		});
		th2.start();

		// 3. 람다 표현식을 사용하여 쓰레드 start()
		new Thread(() -> {
			for (int i = 0; i < 100; i++) {
				System.out.println(i + " : 람다");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

	} // end main()

} // end ThreadMain03
package edu.java.file01;

import java.util.Scanner;

// 프로그램 <== InputStream <=== 입력장치(키보드, 마우스, 파일, ...)
// 프로그램 ===> OutputStream ===> 출력장치(모니터, 프린터, 파일, ...)

public class FileMain01 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		// in : InputStream 클래스의 인스턴스
		// 외부 입력장치(키보드, 마우스)로부터 데이터를 읽어올 수 있는 통로
		
		System.out.println("테스트");
		// out : printStream 클래스의 인스턴스
		// PrintStream은 OutputStream 클래스의 하위 클래스
		// 콘솔화면으로 데이터를 출력하는 통로
		
		
		
	} // end main()

} // end FileMain01
package edu.java.file02;

import java.io.*;

// 프로그램 <=== FileInputStream <=== 파일
// FileInputStream 클래스의 read() 메소드를 사용하여 파일을 읽음

// 프로그램 ===> FileOutputStream ===> 파일
// FileOutputStream 클래스의 write() 메소드를 사용하여 파일에 씀
public class FileMain02 {

	public static void main(String[] args) {
		// temp/original.txt 파일에서 데이터를 읽어서
		// temp/copy.txt 파일에 데이터를 씀
		
		InputStream in = null;
		OutputStream out = null;
		try {
			// FileXXXXStream : 파일 입출력 객체. 통로 역활
			in = new FileInputStream("temp/original.txt");
			out = new FileOutputStream("temp/copy.txt");

			int data = 0; // read() 메소드가 리턴하는 값을 저장할 변수
			int byteCopied = 0;
			
			while (true) {
				// read() : 파일에서 1바이트씩 데이터를 읽어옴
				// 파일 끝에 도달했을 때 -1을 리턴
				data = in.read();
				System.out.println(data);
				if (data == -1) {
					break;
				}

				// write() : 1바이트씩 파일에 씀
				out.write(data);

				byteCopied++;
			}

			System.out.println(byteCopied + "바이트 복사됨");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	} // end main()

} // FileMain02
package edu.java.file03;

import java.io.*;

/*
1. 일반적인 try-catch-finally 구문
try {
	(실행문)
} catch (Exception e) {
	(예외 처리)
} finally {
	(항상 실행할 코드들) // 리소스 삭제
}

2. try-with-resource 구문 : Java 7버전부터 제공
- try() 안에서 생성된 리소스들의 해제 코드(close();)를 자동으로 호출해줌
try(리소스 생성) {
	(실행문)
} catch (Exception e) {
	(예외 처리)
}
*/

public class FileMain03 {

	public static void main(String[] args) {
		InputStream in = null;
		OutputStream out = null;

		try {
			in = new FileInputStream("temp/big_text.txt");
			out = new FileOutputStream("temp/big_copy.txt");

			int data = 0; // read() 메소드가 리턴하는 값을 저장할 변수
			int byteCopied = 0;
			byte[] Buffer = new byte[1024 * 1024 * 10]; // 1MB 공간
			// 1KB = 1024 Bytes
			// 1MB = 1024 * 1024 Bytes
			// 1GB = 1024 * 1024 * 1024 Bytes
			System.out.println("테스트 시작");
			long startTime = System.currentTimeMillis();
			while (true) {
				// read(byte[] b) :
				// 파일에서 읽은 데이터를 매개변수 배열 b에 저장
				// 실제로 읽은 바이트 수를 리턴, 파일 끝에서는 -1을 리턴
				data = in.read(Buffer);
				
				if (data == -1) {
					break;
				}

				// write(byte[] b) :
				// - 매개변수 배열 b의 내용을 한 번에 파일에 씀
				out.write(Buffer);

				byteCopied += data;
			}
			long endTime = System.currentTimeMillis();
			System.out.println("복사 경과 시간 : " + (endTime - startTime));
			System.out.println(byteCopied + "바이트 복사됨");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	} // end main()

} // end FileMain03

file in을 만들때에는 파일을 만들어 주어야 한다
이름이랑 경로가 다르면 안된다.

package edu.java.file04;

import java.io.*;

//프로그램 ===> ObjectOutputStream ===> FileOutputStream ===> 파일(HDD)

public class FileMain04 {

	public static void main(String[] args) {
		OutputStream out = null;
		ObjectOutputStream oout = null;
		
		try {
			out = new FileOutputStream("temp/member.txt");
			oout = new ObjectOutputStream(out);
			
			MemberVO m1 = new MemberVO(1, "root1", "root123");
			oout.writeObject(m1);
			
			MemberVO m2 = new MemberVO(2, "root2", "root123");
			oout.writeObject(m2);
			
			MemberVO m3 = new MemberVO(3, "root3", "root123");
			oout.writeObject(m3);
			
			System.out.println("파일 저장 성공!");

		} catch (Exception e) {
			System.out.println("예외 발생 : " + e.toString());
		} finally {
			try {
				// 리소스(oout)를 해제할 때는 최종적으로 생성된 리소스만 해제하면,
				// 그 리소스(oout)가 사용하고 있는 다른 리소스(out)들도 순차적으로 해제됨
				oout.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	} // end main()

} // end FileMain04

package edu.java.file05;

import java.io.*;

import edu.java.file04.MemberVO;

// 프로그램 <=== ObjectInputStream <=== FileInputStream <=== 파일(HDD)

public class FileMain05 {

	public static void main(String[] args) {
		InputStream in = null;
		ObjectInputStream oin = null;

		try {
			in = new FileInputStream("temp/member.txt");
			oin = new ObjectInputStream(in);
			while (true) {
				try {

					MemberVO m = (MemberVO) oin.readObject(); // 강제형변환
					System.out.println(m);
				} catch (EOFException e) {
					break;
				}
			}

		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				oin.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	} // end main()

} // end FileMain05
package edu.java.file06;

import java.io.*;
import java.util.*;

import edu.java.file04.MemberVO;

// 프로그램 ===> ObjectOutputStream ===>
// BufferedOutputStream ===> FileOutputStream ===> 파일(HDD)
public class FileMain06 {

	public static void main(String[] args) {
		System.out.println("ArrayList<MemberVO> 객체를 파일에 저장하는 코드");

		OutputStream out = null;
		BufferedOutputStream bout = null;
		ObjectOutputStream oout = null;

		try {
			out = new FileOutputStream("temp/list.txt");
			bout = new BufferedOutputStream(out);
			oout = new ObjectOutputStream(bout);

			long startTime = System.currentTimeMillis();
			List<MemberVO> list = new ArrayList<>();
			for (int i = 0; i < 1000; i++) {
				String id = "member" + i;
				String pw = "pw" + i;
				MemberVO m = new MemberVO(i, id, pw);
				list.add(m);
			}
			oout.writeObject(list);
			System.out.println("데이터 저장 완료");

		} catch (Exception e) {
			e.toString();
		} finally {
			try {
				oout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	} // end main()

} // end FileMain06
package edu.java.file07;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;

import edu.java.file04.MemberVO;

public class FileMain07 {

	public static void main(String[] args) {
		/* 데이터 파일을 읽어서 ArrayList의 내용을 출력 */
		InputStream in = null;
		BufferedInputStream bin = null;
		ObjectInputStream oin = null;
		
		try {
			in = new FileInputStream("temp/list.txt");
			bin = new BufferedInputStream(in);
			oin = new ObjectInputStream(bin);
			
			
			ArrayList<MemberVO> list = (ArrayList<MemberVO>) oin.readObject();

			
			for(MemberVO m : list) {
				System.out.println(m);
			}
			
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				oin.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	} // end main()

} // end FileMain07
package edu.java.homework;

import java.io.Serializable;

public class Student implements Serializable {
	private String name;
	private String math;
	private String eng;

	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Student(String name, String math, String eng) {
		this.name = name;
		this.math = math;
		this.eng = eng;
	}

	public String displayInfo() {
		return "Student [name=" + name + ", math=" + math + ", eng=" + eng + "]";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getMath() {
		return math;
	}

	public void setMath(String math) {
		this.math = math;
	}

	public String getEng() {
		return eng;
	}

	public void setEng(String eng) {
		this.eng = eng;
	}

}
package edu.java.homework;

import java.io.*;
import java.util.*;

public class 최정현_HW6 {

	public static void main(String[] args) {
		System.out.println("ArrayList<MemberVO> 객체를 파일에 저장하는 코드");
		Scanner sc = new Scanner(System.in);
		// ArrayList를 이용하여 memberlist.txt안에 내용을 넣기
		OutputStream out = null;
		BufferedOutputStream bout = null;
		ObjectOutputStream oout = null;

		try {
			out = new FileOutputStream("temp/memberlist.txt");
			bout = new BufferedOutputStream(out);
			oout = new ObjectOutputStream(bout);

			List<Student> list = new ArrayList<>();
			for (int i = 0; i < 5; i++) { // 5번 이름, 수학, 영어 넣기
				System.out.println("이름>");
				String name = sc.next();
				System.out.println("수학>");
				String math = sc.next();
				System.out.println("영어>");
				String eng = sc.next();
				Student m = new Student(name, math, eng);
				list.add(m); // list배열에 추가
			}
			oout.writeObject(list);
			System.out.println("데이터 저장 완료");

		} catch (Exception e) {
			e.toString();
		} finally {
			try {
				oout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// ArrayList를 이용하여 memberlist.txt안에 있는 내용을 출력하는 방법
		InputStream in = null;
		BufferedInputStream bin = null;
		ObjectInputStream oin = null;
		
		try {
			in = new FileInputStream("temp/memberlist.txt");
			bin = new BufferedInputStream(in);
			oin = new ObjectInputStream(bin);
			
			ArrayList<Student> list = (ArrayList<Student>) oin.readObject(); // 강제형 변환
			
			for(Student m : list) { // list배열 안에 있는 내용 출력
				System.out.println(m.displayInfo());
			}
			
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			try {
				oin.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		sc.close();

	} // end main

} // end HW_06

0개의 댓글