반응형

1. 일시정지(sleep)

주어진 시간 동안 일시 정지 상태(TIMED_WAITING)가 되고, 다시 실행 대기 상태(RUNNABLE)로 돌아간다.

일시정지 상태에서 주어진 시간이 되기 전에 interrupt() 메소드가 호출되면 InterruptedException이 발생 -> catch에서 실행 대기 상태로 가거나 종료 상태로 갈 수 있도록 한다. 


2. 실행 양보(yield)

실행 대기 상태로 돌아가고, 동일한 우선순위 또는 높은 우선순위를 갖는 다른 스레드가 실행 기회를 가질 수 있게 한다.


2. 다른 스레드의 종료를 기다림(join)

다른 스레드가 종료될 때까지 기다렸다가 실행함


3. wait(), notify(), notifyAll()

  • notify() : 공유객체가 한 스레드가 작업을 완료하면 notify()메소드를 호출해서 일시정지 상태에 있는 한 개의 스레드를 실행대기 상태로 만든다.
  • wait() :  다른 스레드를 실행대기 상태로 만들고 자신은 wait()로 일시정지 상태로 만든다. 
  • notifyAll() : wati()에 의해 이시 정지된 모든 스레드들을 실행 대기 상태로 만든다.
  • 이 메소드들은 동기화 메소드 또는 동기화 블록 내에서만 사용할 수 있다.
  • notify와 wait를 사용할 때 synchronized 를 사용하지 않으면 java.lang.IllegalMonitorStateException이 발생함.

두 개의 스레드가 이용하는 공유 객체.. 일종의 DTO라고 생각하면 될 듯..

Getter -> 데이터가 없으면 wait하고 데이터가 set 되길 기다림 / 데이터가 있으면 반환하고 null로 만듦

Setter -> 데이터가 없으면 data를 set하고 데이터가 있으면 wait하고 get하길 기다림

Data를 Set하는 Thread
Data를 Get하는 Thread
두 스레드를 이용하는 메인 스레드 

 

반응형
반응형
  • 임계영역 : 멀티 스레드 프로그램에서 단 하나의 스레드만 실행할 수 있는 코드 영역


임계영역 지정 방법

1. 동기화 메소드

메소드에 synchronized 붙이기

2. 동기화 블록

일부 내용만 임계영역으로 만들고 싶은 경우

반응형
반응형

멀티 프로세스 : 애플리케이션 단위의 멀티 태스킹

멀티 스레드 : 애플리케이션 내부에서의 멀티 태스킹

  • 하나의 스레드가 예외를 발생시키면 프로세스 자체가 종료될 수 있어 다른 스레드의 영향을 미침.
  • 메인 스레드가 작업 스레드보다 먼저 종료되더라도 작업 스레드가 계속 실행 중이라면 프로세스는 종료되지 않음.

 


스레드 만들기

1. Thread 클래스로부터 직접 생성

java.lang.Thread 클래스로부터 작업 스레드 객체를 직접 생성.

Runnable 인터페이스를 구현한 작업 스레드 클래스
main 스레드

(Runnable 익명 객체를 사용하는 경우)


 

2. Thread 하위 클래스로부터 생성

Thread 클래스를 상속한 후 run메소드를 재정의 

Thread를 상속받은 작업 스레드 클래스
main 스레드

(Thread 익명 객체를 사용하는 경우)

반응형
반응형

예외

1. 일반예외(Exception) : 컴파일러 체크 예외, 자바 소스를 컴파일하는 과정에서 예외 처리 코드가 필요한지 검사함

2. 실행예외(Runtime Exception) : 컴파일하는 과정에서 예외 처리 코드를 검사하지 않음

컴파일 시 예외 처리 확인 여부만 차이가 있고, 모두 예외 처리가 필요함.

모든 예외 클래스들은 java.lang.Exception 클래스를 상속받음.


실행예외(java.lang.RuntimeException 상속)

1. NullPointerException

객체가 없는 상태에서 객체를 사용하려 하면 발생하는 예외

Null인데 참조하면 발생

 

2. ArrayIndexOutOfBoundsException

배열에서 인덱스 범위를  초과하여 사용할 경우 발생

 

3. NumberFormatException

문자를 숫자로 변환할 때 숫자로 변환될 수 있는 문자가 포함되어 있는 경우 발생

Interger.parseInt("a100"); 이런경우 발생

 

4. ClassCastException

억지로 타입변환을 시도할경우 발생

타입 변환 전에 (변환할객체 instanceof 목표객체) 를 사용해서 타입 변환 가능한지 확인~!(결과값 : true/false)


catch 순서

다중 catch블록 작성시 상위 예외 클래스가 하위 예외 클래스보다 아래쪽에 위치해야 함

Exception 클래스는 맨 마지막으로..

 


 

멀티 catch

하나의 catch 블록에서 여러개의 예외를 처리하는 법 

catch 괄호 ()안에서 | 로 연결하면 된다는데

왜 에러가 나지? ㅡ ㅡ

-> 같은 패키지 안에 ArrayIndexOutOfBoundsException이라는 클래스파일을 만들었어서 그랬다... ㅠ ㅠ 


예외 발생시키기 (throw)


예외 떠넘기기 (throws)

  • throws : 메소드 선언부 끝에 작성되어 메소드에서 처리하지 않은 예외를 호출한 곳으로 떠넘김 
  • throws 키워드가 붙은 메소드는 반드시 try 블록 내에서 호출되어야 함.
  • main 메소드에서 throws 사용시 JVM이 최종적으로 예외의 내용을 콘솔에 출력하는 것으로 예외 처리를 한다.
public void method1() throws Exception{
 
}

자동 리소스 닫기(try with resources)

예외 발생 여부와 상관없이 사용했던 리소스 객체의 close() 메소드를 호출해서 리소스를 닫아준다.

  • 조건 : 리소스 객체는 java.lang.QutoCloseable 인터페이스를 구현하고 있어야 함
  • AutoCloseable의 close() 메소드가 자동호출되는거임

AutoCloseable 인터페이스 구현

객체 생성은 다음과 같이~


사용자 정의 예외 클래스

  • 일반예외로 선언할 경우 Exception 상속, 실행예외로 선언할 경우 RuntimeException 상속
  • 생성자는 두 개를 선언하는 것이 일반적 

 


예외 정보 얻기 

  • getMessage() : 예외 발생 시 메시지를 갖는 생성자를 이용한 경우 메세지를 얻어올 수 있음
} catch(Exception e) {
	String message = e.getMessage();
}
  • printStackTrace() : 예외 발생 코드를 추적해서 콘솔에 출력
반응형
반응형

아파치 POI 라이브러리를 이용한 VO LIST 엑셀파일로 출력하기

 

1. 라이브러리 다운

http://poi.apache.org/download.html

 

Apache POI - Download Release Artifacts

Apache POI - Download Release Artifacts Available Downloads This page provides instructions on how to download and verify the Apac

poi.apache.org

 

2. 압축 해제 및 프로젝트에 넣기

(상위에 있는 jar 파일들 포함하여 ooxml-lib, lib 하위의 jar 파일 모두 WEB-INF>lib 에 넣어주기)

3. 컨트롤러에 엑셀 출력을 위한 코드 작성

//엑셀로 출력하기
	@RequestMapping(value="/board/excelDown.do")
	public void excelDown(HttpServletResponse response) throws Exception {
		
		//게시판 목록조회
		List<BoardVo> boardList = boardService.selectAll();
		
        
		//1. 워크북 생성(생성하고자 하는 엑셀 형태에 따른 선언)
		Workbook wb = new XSSFWorkbook(); //xlsx 엑셀 2007 이상


		
		//2. 시트 생성 및 시트명 설정(매개변수를 비우면 default)
		Sheet sheet1 = wb.createSheet("test");
		
        
        
		//3. 열 너비 설정
		sheet1.setColumnWidth(0, 5500);
		sheet1.setColumnWidth(1, 5500);
		sheet1.setColumnWidth(2, 5500);
		sheet1.setColumnWidth(3, 5500);
		sheet1.setColumnWidth(4, 5500);
		
        
        
		//4.테이블 헤더 스타일 지정
		CellStyle headStyle = wb.createCellStyle();
			//데이터 가운데 정렬
		headStyle.setAlignment(HorizontalAlignment.CENTER);
			//경계선
	   	headStyle.setBorderTop(BorderStyle.THIN);
	   	headStyle.setBorderBottom(BorderStyle.THIN);
	   	headStyle.setBorderLeft(BorderStyle.THIN);
	   	headStyle.setBorderRight(BorderStyle.THIN);
	   		// 배경색은 연두색
	   	headStyle.setFillForegroundColor(HSSFColorPredefined.LIGHT_GREEN.getIndex());
	   	headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
	
    
		
		//5. 헤더 생성
		Row row = null;
		Cell cell = null;
		int rowNo = 0;
		
		row = sheet1.createRow(rowNo++);
		
		cell = row.createCell(0);
		cell.setCellStyle(headStyle);
		cell.setCellValue("boardType");
		
		cell = row.createCell(1);
		cell.setCellStyle(headStyle);
		cell.setCellValue("boardNum");
		
		cell = row.createCell(2);
		cell.setCellStyle(headStyle);
		cell.setCellValue("boardTitle");
		
		cell = row.createCell(3);
		cell.setCellStyle(headStyle);
		cell.setCellValue("boardComment");
		
		cell = row.createCell(4);
		cell.setCellStyle(headStyle);
		cell.setCellValue("Creator");
		
        
        
        
		//6. 테이블 바디 스타일 지정
		CellStyle bodyStyle = wb.createCellStyle();
			//데이터 가운데 정렬
		bodyStyle.setAlignment(HorizontalAlignment.CENTER);
			//경계선
		bodyStyle.setBorderTop(BorderStyle.THIN);
		bodyStyle.setBorderBottom(BorderStyle.THIN);
		bodyStyle.setBorderLeft(BorderStyle.THIN);
		bodyStyle.setBorderRight(BorderStyle.THIN);
		
        
        
        
		//7. 데이터 부분 생성
		for(BoardVo vo : boardList) {
		row = sheet1.createRow(rowNo++);
			
		cell = row.createCell(0);
		cell.setCellStyle(bodyStyle);
		cell.setCellValue(vo.getBoardType());
		
		cell = row.createCell(1);
		cell.setCellStyle(bodyStyle);
		cell.setCellValue(vo.getBoardNum());
		
		cell = row.createCell(2);
		cell.setCellStyle(bodyStyle);
		cell.setCellValue(vo.getBoardTitle());
		
		cell = row.createCell(3);
		cell.setCellStyle(bodyStyle);
		cell.setCellValue(vo.getBoardComment());
		
		cell = row.createCell(4);
		cell.setCellStyle(bodyStyle);
		cell.setCellValue(vo.getCreator());
		
		}
		
        
        
		//8. 컨텐츠 타입과 파일명 지정
		response.setContentType("ms-vnd/excel");
		 response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");

		//9. 엑셀 출력
		  wb.write(response.getOutputStream());
		  wb.close();
		

 

출력 예시

setColumnWidth에서 너비 5500을 줬을 때

단위가 뭔지는 모르겠음. . . 

반응형
반응형

Spring Framework에서 Controller인데 

keyfield라는 String 변수와 ""를 비교하는데 죽어도 안먹는거임...

분명히 텍스트가 담겨있는데 자꾸 if에 진입하질 않나..

equals 문제였음

문자열을 비교할땐 equals를 쓰는 습관을 들이자..

 

 

==

* 연산자
* 두 대상의 주소값을 비교함
* 같지 않다는 !=

equals()

* 메소드
* 두 대상의 내용을 비교함
* 같지 않다는 !변수.equals

 

 

 

반응형

+ Recent posts