11장 기본API클래스


■ 객체소멸자

  • GC가 finalize()를 실행하여 객체 소멸

  • 객체가 소멸되기전에 마지막으로 사용한 데이터연결, 파일들을 저장하고 싶을때 finalize()재정의해야한다. 

  • System.gc()는 gc슬행하는 것이다.

  • finalize()는 무작위로 무작위 시점에서 처리된다.

  • major gc할때에는 JVM이 멈춘다. 따라서 major gc가 너무 큰 크기를 처리하지 않도록 적당한 크기를 처리하도록 설정해야한다.


■ Objects 클래스

  • 객체비교, 해시코드생성, null여부, 객체문자열 리턴 연산 수행

  • 객체비교 Objects.compare(T a, T b, Comparator<T>c)). 두 객체를 comparator롤 비교해서 int값 리턴.

  • equals() : 두객체의 동등비교. 같은 객체를 참조하는지 비교.  

  • Objects.deepEquals():  다른배열이라도 같은 내용인지 비교

  • isNull() : 널일때 true 리턴

  • nonNull(): 널이 아닐떄 true 리턴

  • requireNonNull: 널일떄 메시지 출력


■ System 클래스

  • JVM강제종료 : System.exit(0)

  • System.gc() : gc를 빨리 부르는 경우

  • System.currentTimeMills(): 현재시간 millisecnod 단위로 long값을 리턴한다.

  • System.getProperty() : 시스펨프로퍼티는 key, value로 구성되어있다.

  • reflection: Class객체를 사용해서 클래스의 생성자, 필드, 메소드 정보를 알아낼수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        Class clazz = Class.forName("sec06.exam02_reflection.Car");
        
        System.out.println("[클래스 이름]");
        System.out.println(clazz.getName());
        System.out.println();        
        
        System.out.println("[생성자 정보]");
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for(Constructor constructor : constructors) {
            System.out.print(constructor.getName() + "(");
            Class[] parameters = constructor.getParameterTypes();
            printParameters(parameters);
            System.out.println(")");
        }        
        System.out.println();
cs
  • newInstance(): new 연산자를 상용하지 않고 동적으로 객체를 생성할 수 있다. 물론 클래스에 기본생성자가 존재하는 경우에만. 그리고 반환된 인스턴스는 Object타입이므로 캐스팅해서 사용한다. 

■ String 클래스

  • String생성자 : byte 배열을 문자열로 변환하기 위해 하는 경우. 문자셋이 다른경우 디코딩 할떄 사용된다.

  • String메소드: charAt(인덱스), equals(내용비교할문자열), getByte(" 인코딩문자셋타입")->네트워크로 문자열 전송하고나 문자열 암호화할때, substring(), replace(타겟,바꿀내용), indexOf(찾고싶은문자열),length(),trim()->앞뒤 공백 잘라내기를 하지만 원래문자열은 그대로 있고 공백이 잘라내진 새로운 String을 리턴한다., valueOf(기본타입)-> 기본타입을 문자열로 바꿈 등등...


■ StringTokenizer 클래스

  • split() : 정규표현식을 구분자로해서 문자열을분리한 후 배열에 저장하고 리턴한다.

1
2
3
4
String []reuslt="문자열".split("정규표현식");
cs
  • StringTokenizer : 문자열이 한종류의 구분자로 연결되어있을 경우 사용. countTokens(), hasMoreTokens(), nexToken() -> 토근을 하나씩 꺼내옴.
1
2
3
4
StringTokenizer st= new StringTokenizer("문자열""구분자");
cs
  • StringBuffer : Stirng은 내부의 문자열을 대치하는ㄴ 것이 아니라 새로운 문자열을 리턴하기 때문에 StringBuffer를 쓴다. StringBuilder는 StringBuffer와 같지만 단일스레드에서만 사용하기때문에 쓰지않는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        
        sb.append("Java ");
        sb.append("Program Study");
        System.out.println(sb.toString());
        
        sb.insert(4"2");
        System.out.println(sb.toString());
 
        sb.setCharAt(4'6');
        System.out.println(sb.toString());
        
        sb.replace(613"Book");
        System.out.println(sb.toString());
        
        sb.delete(45);
        System.out.println(sb.toString());
        
        int length = sb.length();
        System.out.println("총문자수: " + length);
        
        String result = sb.toString();
        System.out.println(result);        
    }
}
cs


■ 정규표현식과 Pattern 클래스

  • 문자열이 정규표현식으로 구성되어있는지 검증(ex 이메일, 전화번호를 사용자가 제대로 입력했는지)


■ Arrays 클래스

  • Arrays.copyOf(원본배열, 복사할 길이)


■ Wrapper 클래스

  • 문자열이 정규표현식으로 구성되어있는지 검증(ex 이메일, 전화번호를 사용자가 제대로 입력했는지)


■ Math,Random 클래스

  • Math.random은 0<=x<1

  • Random(종자값)은 타입별로 난수를 얻을 수 있다.

■ Format 클래스

  • 단위구분



12장 멀티스레드


■ 멀티스레드 개념

  • 프로세스 : 실행중인 하나의 어플리케이션

  • 멀티프로세스 : 하나의 프로세스에서 예외가 발생해도 다른 프로세스에는 영향을 미치지 않는다.

  • 멀티태스킹 : 두가지 이상의 작업을 동시에 처리

  • 스레드 : 한가지 작업을 실행하기 위해 순차적으로 실행할 코드. 코드실행흐름

  • 멀티스레드 : 하나의 프로세스 내부에서 발생한 여러개의 스레드

  • 멀티스레드는 하나의 프로세스 내부에서 생성되기 때문에 하나의 스레드가 예외를 발생시키면 프로세스 자체가 종료될 수 있다. 

  • 메인스레드는 멀티스레드를 생성해서 멀티태스킹 가능. 멀티스레드에서는 메인스레드가 종료되어도 실행중인 스레드가 있으면 프로세스는 종료되지 않는다.


■ 작업 스레드 생성과 실행

  • 메인스레드는 반드시 존재한다.

  • Thread 클래스로부터 직접 객체화해서 생성도 가능

  • Runnable은 작업스레드가 실행할 수 있는 코드를 가지고 있다는 의미. run()을 재정의해서 작업스레드가 실행해야할 코드를 작성해야한다.

  • Runnable은 인터페이스 타입이기 때문에 구현객체를 만들어서 대입해야한다.

1
2
3
4
5
6
7
8
9
public class Example {
    public static void main(String[] args) {
        Thread thread= new Thread(new Runnable(){
            public void run(){
                //스레드가 실행할 내용
            }
        });
    }
}
cs
  • thread.start()를 호출해야만 실행된다. run()메소드를 실행하며 자신의 작업을 처리한다.
  • 1. Thread 클래스로부터 직접 생성
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class BeepPrintExample2 {
    public static void main(String[] args) {
        //how1
        Runnable beepTask = new BeepTask();
        Thread thread = new Thread(beepTask);
        
        //how2
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Toolkit toolkit = Toolkit.getDefaultToolkit();    
                for(int i=0; i<5; i++) {        
                    toolkit.beep();
                    try { Thread.sleep(500); } catch(Exception e) {}
                }
            }
        });
        
        //how3
        Thread thread = new Thread(() -> {
            Toolkit toolkit = Toolkit.getDefaultToolkit();    
            for(int i=0; i<5; i++) {        
                toolkit.beep();
                try { Thread.sleep(500); } catch(Exception e) {}
            }
        });
        
        thread.start();
        
        for(int i=0; i<5; i++) {
            System.out.println("띵");
            try { Thread.sleep(500); } catch(Exception e) {}
        }
    }
}
cs
  • 2. Thread 하위 클래스로부터 생성
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package sec02.exam01_createthread;
 
import java.awt.Toolkit;
 
public class BeepPrintExample3 {
    public static void main(String[] args) {
        //how1
        Thread thread = new BeepThread();
        
        //how2
        Thread thread = new Thread() {
            @Override
            public void run() {        
                Toolkit toolkit = Toolkit.getDefaultToolkit();    
                for(int i=0; i<5; i++) {        
                    toolkit.beep();
                    try { Thread.sleep(500); } catch(Exception e) {}
                }
            }
        };
        
        
        thread.start();        
        
        for(int i=0; i<5; i++) {
            System.out.println("띵");
            try { Thread.sleep(500); } catch(Exception e) {}
        }
    }
}
 
 
cs
  • thread.setName("이름");
  • thread.getName();
  • 현재쓰래드 : Thread.currentThread();

■ 스레드 우선순위

  • 동시성 : 멀티작업을 위해 하나의 코어에서 멀티스레드가 번갈아가며 실행하는 성질

  • 병렬성 : 멀티작업을 위해 멀티코어에서 개별스레드를 동시에 실행하는 성질

  • 스레드 스케줄링 : 스레드를 어떤순서에 의해 동시성으로 실행할지 결정하는 일

  • Priority 방식 : 우선순위대로 스케줄링

  • Round-Robin : Time slice 만큼 번걸아가면서 실행하는 방식

  • thread.setPriority(우선순위)


■ 동기화 메소드와 동기화블록

  • 멀티스레드 프로그램에서는 스레드들이 객체를 공유해서 작업해야한다.

  • 스레드A가 변경중인 객체가 스레드 B에 의해 변경된 상태이면 의도와 다르게 결과가 나타난다.

  • 이를 위해 객체에서 syncronized를 사용해서 임계영역을 정한다. 

  • syncronized(공유객체){임계영역}

  • 혹은 syncronized 메소드이름



'Web Programming > Java' 카테고리의 다른 글

Poi 라이브러리 활용  (0) 2018.04.03
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package com.gsitm.java.poi;
 
import java.io.FileOutputStream;
 
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderExtent;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.PropertyTemplate;
import org.apache.poi.ss.util.RegionUtil;
 
/**
 * @Project : test
 * @Date : 2018. 4. 4.
 * @작성자 : 뿌따따
 * @프로그램 설명 : Poi 활용.
 */
public class Poi_1062 {
 
    static HSSFRow row;
    static HSSFCell cell;
 
    public static void main(String[] args) {
        // 엑셀파일을 생성한다.
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 시트를 만든다. mysheet
        HSSFSheet sheet = workbook.createSheet("mySheet");
 
        // 셀병합
        sheet.addMergedRegion(CellRangeAddress.valueOf("B3:D3"));
        sheet.addMergedRegion(CellRangeAddress.valueOf("A5:A6"));
        sheet.addMergedRegion(CellRangeAddress.valueOf("B5:D5"));
        sheet.addMergedRegion(CellRangeAddress.valueOf("B6:D6"));
        sheet.addMergedRegion(CellRangeAddress.valueOf("B8:D8"));
        sheet.addMergedRegion(CellRangeAddress.valueOf("B9:D9"));
        // 셀너비 설정
        sheet.setColumnWidth(0, (int18.25 * 256 + 200);
        sheet.setColumnWidth(1, (int36.25 * 256 + 200);
        sheet.setColumnWidth(2, (int18.25 * 256 + 200);
        sheet.setColumnWidth(3, (int36.25 * 256 + 200);
 
        // 폰트설정
        Font font = workbook.createFont();
        font.setFontName("맑은 고딕");
        font.setBold(true);
 
        // 아무것도 내용없는 셀의 스타일 설정
        HSSFCellStyle borderStyle = workbook.createCellStyle();
        borderStyle.setBorderBottom(BorderStyle.THIN);
        borderStyle.setBorderLeft(BorderStyle.THIN);
        borderStyle.setBorderRight(BorderStyle.THIN);
        borderStyle.setBorderTop(BorderStyle.THIN);
 
        // 배경 노란색인 셀의 스타일 설정
        HSSFCellStyle yellowStyle = workbook.createCellStyle();
        yellowStyle.cloneStyleFrom(borderStyle);
        yellowStyle.setFillForegroundColor(new HSSFColor.YELLOW().getIndex());
        yellowStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
 
        yellowStyle.setFont(font);
        yellowStyle.setAlignment(HorizontalAlignment.CENTER);
        yellowStyle.setVerticalAlignment(VerticalAlignment.CENTER);
 
        // 노란색 배경은 없지만 글씨가 있는 셀의 스타일 설정
        HSSFCellStyle fontStyle = workbook.createCellStyle();
        fontStyle.cloneStyleFrom(borderStyle);
        fontStyle.setFont(font);
 
        // 첫번째 row부터 차례대로 생성
        row = sheet.createRow(0);
        row.setHeightInPoints((float20.3);
        row.createCell(0).setCellValue("프로젝트명");
        row.createCell(1);
        row.createCell(2).setCellValue("프로젝트 규모");
        row.createCell(3);
 
        row = sheet.createRow(1);
        row.setHeightInPoints((float20.3);
        row.createCell(0).setCellValue("작성자");
        row.createCell(1);
        row.createCell(2).setCellValue("작성일");
        row.createCell(3);
 
        row = sheet.createRow(2);
        row.setHeightInPoints((float69.9);
        row.createCell(0).setCellValue("프로젝트 제약사항");
        row.createCell(1);
        row.createCell(2);
        row.createCell(3);
 
        row = sheet.createRow(3);
        row.setHeightInPoints((float6);
 
        row = sheet.createRow(4);
        row.setHeightInPoints((float20.3);
        row.createCell(0).setCellValue("확인");
        row.createCell(1).setCellValue(
                " 프로젝트");
        row.createCell(2);
        row.createCell(3);
 
        row = sheet.createRow(5);
        row.setHeightInPoints((float20.3);
        row.createCell(0);
        row.createCell(1).setCellValue(
                " 프로젝트 관리자 :   ");
        row.createCell(2);
        row.createCell(3);
 
        row = sheet.createRow(6);
        row.setHeightInPoints((float6);
 
        row = sheet.createRow(7);
        row.setHeightInPoints((float69.9);
        row.createCell(0).setCellValue("검토의견");
        row.createCell(1);
        row.createCell(2);
        row.createCell(3);
 
        row = sheet.createRow(8);
        row.setHeightInPoints((float20.3);
        row.createCell(0).setCellValue("검토자");
        row.createCell(1).setCellValue(
                "담당자 :  ");
        row.createCell(2);
        row.createCell(3);
 
        // 전체 셀에 가는선을 입히고 굵은글씨로 만드는 스타일 적용
        for (Sheet sheet2 : workbook) {
            for (Row row : sheet2) {
                for (Cell cell : row) {
                    if (cell.getStringCellValue().isEmpty()) {
                        cell.setCellStyle(borderStyle);
                    } else if (cell.getStringCellValue().isEmpty() == false) {
                        cell.setCellStyle(fontStyle);
                    }
                }
            }
        }
 
        // 노란색 백그라운드를 가진 셀에 대하여 스타일 적용
        for (Sheet sheet1 : workbook) {
            for (Row row : sheet1) {
                for (Cell cell : row) {
                    if (cell.getAddress().getColumn() == 0) {
                        cell.setCellStyle(yellowStyle);
                    }
                    if (cell.getAddress().getColumn() == 2
                            && (cell.getAddress().getRow() == 0 || cell.getAddress().getRow() == 1)) {
                        cell.setCellStyle(yellowStyle);
                    }
                }
            }
        }
 
        // 굵은선 적용
        RegionUtil.setBorderBottom(BorderStyle.THICK, CellRangeAddress.valueOf("A5:D6"), sheet);
        RegionUtil.setBorderRight(BorderStyle.THICK, CellRangeAddress.valueOf("D1:D6"), sheet);
        RegionUtil.setBorderBottom(BorderStyle.THICK, CellRangeAddress.valueOf("A9:D9"), sheet);
        RegionUtil.setBorderTop(BorderStyle.THICK, CellRangeAddress.valueOf("A8:D8"), sheet);
        RegionUtil.setBorderRight(BorderStyle.THICK, CellRangeAddress.valueOf("D8:D9"), sheet);
 
        // 파일로 출력한다.
        FileOutputStream outFile;
 
        try {
            outFile = new FileOutputStream("C:\\aa\\test.xls");
            workbook.write(outFile);
            outFile.close();
 
            System.out.println("파일생성완료");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
cs


'Web Programming > Java' 카테고리의 다른 글

04/05 Java 기본 API 클래스~  (0) 2018.04.05

+ Recent posts