BootCamp 31day

GyeongNamΒ·2024λ…„ 1μ›” 1일
0

BootCamp

λͺ©λ‘ 보기
29/49
post-thumbnail

πŸ“… 2023λ…„ 12μ›” 27일

[java 16일차]


31일차: java 심화(9)

파일 처리

  • 슀트림(stream)
    μžλ°”μ—μ„œλŠ” νŒŒμΌμ΄λ‚˜ μ½˜μ†”μ˜ μž…μΆœλ ₯을 직접 λ‹€λ£¨μ§€μ•Šκ³ , μŠ€νŠΈλ¦Όμ„ μ΄μš©ν•œλ‹€.
    λ™μ‹œμ— μˆ˜ν–‰ν•˜λ €λ©΄ μž…λ ₯슀트림과 좜λ ₯슀트림 λͺ¨λ‘ ν•„μš”ν•˜κ³  큐(queue)와 같은 FIFO ꡬ쑰둜 이루어져 μžˆλ‹€.

  • file

/*
버퍼 κΈ°λŠ₯이 κ΅¬ν˜„λ˜μ–΄μžˆκ³ , nio νŒ¨ν‚€μ§€μ—μ„œλŠ” non-blocking 방식 μ‚¬μš©
기본이 StandardCharsets.UTF_8 이닀.
*/
Path filePath = Paths.get("src/C17_Exception_File_Parsing/text_file.txt"
try {
	if(Files.exists(filePath)){
		Files.write(filePath, "손ν₯λ―Ό\n".getBytes(), StandardOpenOption.WRITE);
	}else{
		Files.write(filePath, "손ν₯λ―Ό\n".getBytes(), StandardOpenOption.CREATE_NEW);
	}
}catch (IOException e){
	e.printStackTrace();
}
// 파일 일기 : readString , readAllLines(List ν˜•νƒœ)
try {
	String str = Files.readString(filePath);
	System.out.println(str);
}catch (IOException e){
	e.printStackTrace();
}
System.out.println();
try {
	List<String> stringList = Files.readAllLines(filePath);
	for(String str :stringList){
		System.out.println(str);
	}
}catch (IOException e) {
	e.printStackTrace();
}
  • json
 // http 클라 생성
 HttpClient client = HttpClient.newHttpClient();
 ObjectMapper mapper = new ObjectMapper();
 // http μš”μ²­κ°μ²΄ 생성
 HttpRequest request = HttpRequest.newBuilder()
               .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
                .GET()
                .build();
HttpRequest request1 = HttpRequest.newBuilder()
                .uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
                .GET()
                .build();
// http 응닡 객체 생성
try {
	HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
	JsonNode node = mapper.readTree(response.body());
	Post post = new Post(
		node.get("userId").asInt(),
		node.get("id").asInt(),
		node.get("title").asText(),
		node.get("body").asText()
	);
	Post post1 = mapper.readValue(response.body(),Post.class);
	/*
	json NodeλŠ” 트리ꡬ쑰 μ΄λ―€λ‘œ,
	for(JsonNode a : jsonNode) ν˜•μ‹μœΌλ‘œ μ‚¬μš©κ°€λŠ₯
	*/
	HttpResponse<String> response1 = client.send(request1, HttpResponse.BodyHandlers.ofString());
	ArrayList<Post> postArrayList = new ArrayList<>();
	JsonNode node1 = mapper.readTree(response1.body());
	for(JsonNode a : node1){
//  	Post post3 = new Post(
//  		a.get("userId").asInt(),
//  		a.get("id").asInt(),
//  		a.get("title").asText(),
//   		a.get("body").asText()
//      );
	Post post3 = mapper.readValue(a.toString(),Post.class);
	postArrayList.add(post3);
}
System.out.println(postArrayList);
// java 객체λ₯Ό json λ°μ΄ν„°λ‘œ μ •λ ¬ν™”
String serialized_data = mapper.writeValueAsString(postArrayList);
System.out.println(serialized_data);
} catch (IOException | InterruptedException e) {
	throw new RuntimeException(e);
}

μŠ€λ ˆλ“œ(Thread)

/*
Thread ν΄λž˜μŠ€μ— 이미 κ΅¬ν˜„λ˜μ–΄ μžˆλŠ” run λ©”μ„œλ“œλŠ” μ•„λ¬΄μž‘μ—…λ„ ν•˜μ§€ μ•ŠλŠ” 빈 λ©”μ„œλ“œ
μž‘μ—…ν•˜κ³  싢은 λ‚΄μš©μ€ run() λ©”μ„œλ“œλ₯Ό overriding ν•˜μ—¬ μ •μ˜ν•  수 μžˆλ‹€.
상솑관계이닀 λ³΄λ‹ˆ, λ‹€λ₯Έ 클래슀 상속 λΆˆκ°€
 */
public class ExtendsThreadClass extends Thread{
    // run λ©”μ„œλ“œλŠ” μ“°λ ˆλ“œκ°€ μ‹œμž‘λ˜λ©΄ μ‹€ν–‰
    @Override
    public void run(){
        System.out.println("ExtendsThreadClass : " + Thread.currentThread().getName());
    }
}
public class RunnableImplementsClass implements Runnable {
    @Override
    public void run() {
        System.out.println("RunnableImplementsClass : "+ Thread.currentThread().getName());
    }
}
public class Library {
    static int bookCount = 100;
//    public  static  void barrowBook(){
//        if(bookCount>0){
//            try{
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//
//            // μ±… λΉŒλ¦¬λŠ” μ‹œκ°„
//            bookCount -= 1;
//            System.out.println("λŒ€μΆœ μ™„λ£Œ");
//            System.out.println("λ‚¨μ•„μžˆλŠ” μˆ˜λŸ‰: " +bookCount);
//        }else{
//            System.out.println("λŒ€μΆœ λΆˆκ°€");
//        }
//    }
    // synchronized ν‚€μ›Œλ“œλ₯Ό 톡해 ν•΄λ‹Ή λ©”μ„œλ“œ ν•œν•΄μ„œλŠ” lock걸도둝 μ„€μ •
    public synchronized static void barrowBook(){
        if(bookCount>0){
            try{
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // μ±… λΉŒλ¦¬λŠ” μ‹œκ°„
            bookCount -= 1;
            System.out.println("λŒ€μΆœ μ™„λ£Œ");
            System.out.println("λ‚¨μ•„μžˆλŠ” μˆ˜λŸ‰: " +bookCount);
        }else{
            System.out.println("λŒ€μΆœ λΆˆκ°€");
        }
    }
}
public class MainClass {
    public static void main(String[] args) {
        Thread etc1 = new ExtendsThreadClass();
        etc1.start();
        Thread etc2 = new ExtendsThreadClass();
        etc2.start();
        Thread etc3 = new ExtendsThreadClass();
        etc3.start();
        // μŠ€λ ˆλ“œ μ‹€ν–‰ μ‹œ 순차적으둜 μ‹€ν–‰λ˜μ§€ μ•ŠμŒμ— 유의
        // μŠ€λ ˆλ“œ μƒμ„±μžλ‘œ Runnable 객체가 μ „λ‹¬λ˜μ–΄ μ‚¬μš©μžκ°€ 직접 μ •μ˜ run λ©”μ„œλ“œκ°€ μ‹€ν–‰
        new Thread(new RunnableImplementsClass()).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("읡λͺ…객체 μŠ€λ ˆλ“œ");
            }
        }).start();
        new Thread(() -> System.out.println("읡λͺ…객체 λžŒλ‹€ μŠ€λ ˆλ“œ")).start();
        // μŠ€λ ˆλ“œμ˜ λ™μ‹œμ„± 이슈 ν…ŒμŠ€νŠΈ
        // 단일 μŠ€λ ˆλ“œ 일반호좜
        for (int i =0; i<1000; i++){
            Thread th = new Thread(Library::barrowBook);
            th.start();
            // joinλ©”μ„œλ“œλ₯Ό 톡해 λ‹€λ₯Έ μŠ€λ ˆλ“œμ˜ μ™„λ£Œμ „κΉŒμ§€ μƒˆλ‘œμš΄ μŠ€λ ˆλ“œκ°€ μ‹€ν–‰λ˜μ§€ μ•Šλ„λ‘ λ§‰μŒ.
//            try {
//                th.join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
        System.out.println("μ΅œμ’… 남은 μˆ˜λŸ‰ "+ Library.bookCount);
    }
}
  • ν”„λ‘œμ„ΈμŠ€μ™€ μŠ€λ ˆλ“œ
    ν”„λ‘œμ„ΈμŠ€ : cpu에 μ˜ν•΄ λ©”λͺ¨λ¦¬μ— 올렀져 싀행쀑인 ν”„λ‘œκ·Έλž¨
    μŠ€λ ˆλ“œ : μ‹€μ§ˆμ μœΌλ‘œ μž‘μ—…μ„ μ‹€ν–‰ν•˜λŠ” λ‹¨μœ„
    ν”„λ‘œμ„ΈμŠ€μ—λŠ” 적어도 ν•œκ°œ μ΄μƒμ˜ μŠ€λ ˆλ“œκ°€ 있으며, Main μŠ€λ ˆλ“œ ν•˜λ‚˜λ‘œ μ‹œμž‘ν•˜μ—¬ μŠ€λ ˆλ“œλ₯Ό μΆ”κ°€ μƒμ„±ν•˜κ²Œ 되면 λ©€ν‹° μŠ€λ ˆλ“œ ν™˜κ²½μ΄ λœλ‹€.
  • Thread 클래슀λ₯Ό μƒμ†λ°›λŠ” 방법과 λ‹€λ₯Έ ν•˜λ‚˜λŠ” Runnable μΈν„°νŽ˜μ΄μŠ€λ₯Ό κ΅¬ν˜„ν•˜λŠ” 방법.
  • λ©€ν‹°μŠ€λ ˆλ“œμ˜ λ™μ‹œμ„±λ¬Έμ œλ₯Ό java에선 join() λ˜λŠ” syncronized으둜 ν•΄κ²°.
    • join() : ν•œ μŠ€λ ˆλ“œκ°€ μ™„λ£Œλ λ•ŒκΉŒμ§€ λ‹€λ₯Έ μŠ€λ ˆλ“œμ˜ startλ₯Ό ν•˜μ§€ μ•Šλ„λ‘ ν•  λ•Œ μ‚¬μš©
    • syncronized: race condition이 λ°œμƒν•  수 μžˆλŠ” μ½”λ“œ μ˜μ—­μ„ λ³΄ν˜Έν• λ•Œ μ‚¬μš©

github java μ‹€μŠ΅ λ‚΄μš©

profile
503 Service Unavailable Error

0개의 λŒ“κΈ€