일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 영화예매
- ssh
- AWS RDS
- topologySpreadConstraints
- mysql
- spring
- 인생이재밌다
- 예매로직
- html
- Java
- json
- MySQL Error
- node.js
- chartjs
- Get
- mongodb
- Bootstrap
- sessionStorage
- post
- AWS
- terminationGracePeriodSeconds
- git
- ES6
- javascript
- ajax
- jsp
- spread operator
- zombie-hit apartment
- Kubernetes
- AWS Route53
- Today
- Total
jongviet
Mar 2, 2021 - Java 13일차 본문
#Java
*3월2일
-전부다 cramming만 하지 말고, 아는 것 내에서 활용도를 높여가보자.
1)컴퓨터 시간 가져오기 / 기능 활용하여 경과 시간 확인하기
-long time1 = System.currentTimeMillis(); // 컴퓨터 현재 시간 가져오기
-long time2 = System.currentTimeMillis() - time1; // 경과시간
*경과시간 확인 with 타이머
//thread와 currentTimeMillis를 100% 일치시킬 수 없어 정확도는 낮음.
MyThread th1 = new MyThread();
th1.start(); //시간경과
long time1 = System.currentTimeMillis();
while(tempArr.size() > 0) {
int ranNum = new Random().nextInt(tempArr.size()); // 0~2번 값 ok,,
String[] arr = tempArr.get(ranNum).split(","); //
System.out.println(arr[0]); //영어 단어만 노출
input = sc.nextLine();
if (arr[1].equals(input)) { //ok
System.out.println("정답~");
}
else {
System.out.println("공부쫌해라~");
}
tempArr.remove(ranNum);
}
th1.stop();
long time2 = System.currentTimeMillis() - time1;
System.out.println("경과시간:" + time2 / 1000 + "초");
2)Object class
-모든 클래스의 부모클래스
-어떤 데이터 타입인지 모를 때 object class로 받으면 됨.. (primitive는 제외)
-instance = 객체
-library가 워낙잘되어있어서 math class에 대한 사용률이 낮음..
3)Nested class(inner class 포함)
-개념만 이해해야지, 너무 깊이 팔 필요 없음.
-중첩; 클래스나 인터페이스 안에 클래스를 선언하거나 인터페이스를 선언한 형태
-nested class안에 static nested class, inner class, local inner class 가 있음.
-다른 클래스를 에워싼 클래스를 enclosing class라고 함.
-장점은 코드 읽기 편하고, 파일 개수 줄여줌.
-이너 클래스 외부인 main에서 사용 가능하긴 하지만, 최대한 쓰지마라.. 따로 자바 파일 만들어서 쓰는게 훨 나음..
-처음 공부할때는 그냥 파일 다 따로 쓰자…
-java는 전체적으로 한 번 읽고 complie을 함.
-nested interface 사용 이유는?? 일반 인터페이스랑 큰 차이 없음,, 그냥 개발자가 원하는 바에 따라 사용
*inner class화 해보기
public class Control {
//Control에서만 쓰므로 inner class로 만들기~
class MyThread extends Thread {
@Override
public void run() {
for(int i = 1; i < 301; i++) {
System.out.println("경과시간:" + i + "초");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
4)Multithread
-JAVA는 순차처리가 기본이다.. 순서를 따라가면 하나의 흐름이고, 이게 곧 thread임.
-이때까지 작업한 것은 모두 single thread program임.
-실제 multi thread는 일어나는 것처럼 보이나,, 컴퓨터가 작은 간격으로 일을 번갈아 실행하는 것으로 그 시간과 순서는 하드웨어나 시스템 환경에 따라 달라질 수 있음.
-멀티쓰레드는 프로그램에서 메인 쓰레드가 종료되었을때 프로그램이 끝나는 것이 아니라 모든 프로그램이 끝나야 종료된다.
-게임 기준, 충돌, 적군인지, 내 시야 등등등…. 따라서 thread.sleep 적용하여 각각 기능에 텀을 줘야함. 아니면 컴퓨터 뻑감..
-thread class는 기본 제공
*multi thread 예제
//run method는 start로 실행해야함
//start method는 thread에서 한 번만 실행됨.
package main;
public class Main {
public static void main(String[] args) {
MyThread th1 = new MyThread();
th1.start(); //thread는 스타트 한 번 밖에 안됨
MyThread2 th2 = new MyThread2();
th2.start();
for(int i = 0; i < 30; i++) {
System.out.println("main:" + i);
}
}
}
package main;
public class MyThread extends Thread{
@Override
public void run() {
for(int i = 0; i < 30; i++) {
System.out.println("thread:" + i);
}
}
}
package main;
public class MyThread2 extends Thread {
@Override
public void run() {
for(int i = 0; i < 30; i++) {
System.out.println("thread2:" + i);
}
}
}
*Console
//왔다 갔다 하면서실행되지만 인간 입장에서는 동시에 실행되는 것처럼 보임..
thread:0
thread:1
thread:2
thread:3
thread:4
thread:5
thread:6
thread:7
main:0
thread:8
main:1
main:2
main:3
main:4
thread2:0
thread:9
thread:10
thread2:1
thread2:2
thread2:3
thread2:4
thread2:5
thread2:6
thread2:7
thread2:8
thread2:9
thread2:10
thread2:11
thread2:12
thread2:13
thread2:14
thread2:15
thread2:16
main:5
thread2:17
thread:11
thread2:18
main:6
thread2:19
thread:12
thread2:20
main:7
thread2:21
thread:13
thread:14
thread2:22
main:8
thread2:23
thread:15
thread2:24
main:9
main:10
main:11
main:12
main:13
main:14
main:15
thread2:25
thread:16
thread:17
thread2:26
thread2:27
thread2:28
thread2:29
main:16
thread:18
main:17
thread:19
main:18
thread:20
main:19
thread:21
main:20
thread:22
thread:23
thread:24
thread:25
thread:26
thread:27
thread:28
thread:29
main:21
main:22
main:23
main:24
main:25
main:26
main:27
main:28
main:29
5)thread sleep
-일정 시간이 경과 되기를 기다리는 메소드..
-mills 밀리세컨 단위, 1/1000초, 1000 = 1초라는 것.
-중간중간에 thread.sleep 넣어줘야 컴퓨터 과부하를 막을 수 있음,, 최소한 필요한 만큼만 구현하면 되기에..
for(int i = 0; i < 10; i++) {
System.out.println("main:" + i);
try {
Thread.sleep(1000); //intermission 타임 추가
} catch (InterruptedException e) {
e.printStackTrace();
}
}
6)main이 아닌 타 class에서 다른 class 호출
-Share share; 클래스명.불러올명칭
-new 처리는 불필요, 그냥 사용하겠다고 들고 오는 것.
7)thread 작업 순서 확실히 하기
-각자 독립된 thread끼리의 작업은 타 thread가 변경되어도 인지하지 못함 왜냐하면 최초 값 기준으로 참조하기에!
-즉, Boolean done은 thread2가 아닌 thread1에서만 변경되기에… 공용 class인 share의 boolean done앞에 volatile을 붙여 줘서 해당 값을 항상 가져다가 체크하게 만들어야 함.
public class MyThread1 extends Thread {
Share share;
@Override
public void run() {
for(int i = 0; i < 100; i++) {
for(int j = 0; j < 100; j++) {
if(j % 2 == 0) {
share.num += 100;
}
else {
share.num -= 100;
}
}
}
share.num = -1;
share.done = true;
}
}
public class MyThread2 extends Thread {
Share share;
@Override
public void run() {
while(share.done == false) {
}
System.out.println("th2등장: " + share.num);
}
}
public class Share {
int num;
//클래스 내 변경하는 코드 없을 경우, volatile 적을 시 실제 메모리로 가서 확인 후 처리함.
volatile boolean done = false;
}
public class Main {
public static void main(String[] args) {
Share share = new Share();
MyThread1 th1 = new MyThread1();
th1.share = share;
MyThread2 th2 = new MyThread2();
th2.share = share;
th1.start();
th2.start();
}
}
8)thread 상속 불가 -> 인터페이스로 사용
-상속도 쓰고, thread도 쓰고 싶을때..
public class Main {
public static void main(String[] args) {
//인터페이스 thread 사용법
Thread th = new Thread(new MyThread());
th.start();
}
}
public class MyThread implements Runnable {
@Override
public void run() {
System.out.println("thread~");
}
}
9)Synchronized
-thread의 경우 각각 독립된 객체로 오류가 많이남.. 따라서 특정한 작업 실행되는 도중에 다른게 실행될 수 없게 synchronized로 묶어줌..
public class Transfer implements Runnable {
Share share;
@Override
public void run() {
System.out.println("thread~");
for (int i = 0; i < 10; i++) {
synchronized(share) {
share.ac2.balance -= 100;
System.out.println("100원 인출");
//사이에 끼어 들 수 없음,,
share.ac1.balance += 100;
System.out.println("100원 입금");
}
}
}
}
'Java' 카테고리의 다른 글
Mar 4, 2021 - Java 15일차 (0) | 2021.03.04 |
---|---|
Mar 3, 2021 - Java 14일차 (0) | 2021.03.04 |
Feb 26, 2021 - Java 12일차 (0) | 2021.03.01 |
Feb 25, 2021 - Java 11일차(블로그 이전 재작성) (1) | 2021.03.01 |
Feb 24, 2021 - Java 10일차(블로그 이전 재작성) (0) | 2021.03.01 |