jongviet

Mar 2, 2021 - Java 13일차 본문

Java

Mar 2, 2021 - Java 13일차

jongviet 2021. 3. 2. 19:14

#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원 입금");

 

}

 

}

}

 

}

Comments