본문 바로가기

IT&코딩/국비지원

네트워크 - 1 (네트워크 이론 및 스레드)

728x90
반응형

■ 이론

 

ISO : International Standart Orhanization

OSI : Open System Interconnection (글로벌 통신 규약)

 

osi 7 layer : 7계층

 

□ Network

 

- 근거리 및 원거리 사이의 컴퓨터 연결을 통해 데이터를 통신하는 망.

- 데이터 공유가 가능

 

종류 : LAN(Local Area Network), WAN(Wide-lan), AT&T

 


 

Please Do Not Throw Sausage Pizza Away

 

□ 캡슐화, 디캡슐화

: layer 전송시마다 header, footer가 붙어 신뢰성 보장 및 각 layer에서 인식가능 하도록 함.

 

□ ISO 7계층

 

1) Application layer (응용)

 

user에게 network 리소스에 대한 서비스를 제공. SMTP(심플 메일) 등의 서비스를 제공.

http(하이퍼텍스트), ftp(파일) 등의 protocol

 

- protocol data unit ==> 데이터 전송단위(PDU)

- A-PDU? data(message)

 

2) Presentation (표현)

 

네트워크의 다양한 데이터 표현방법들을 하나로 통일시키는 역할로 입출력 데이터를 하나의 표현으로 변환하는 역할 등을 말한다. (encoding, decoding 등을 수행)

 

- P-PDU? data

 

3) Session

 

연결을 안정적으로 유지하거나 처리완료 후 연결을 종료하는 역할

 

- S-PDU? date

 

4) Transport  (전송)

 

장비 사이의 안정적인 통신 보장

신뢰성 전달 보장이 목적, 전체 데이터를 잘 전송한다.

 

- TCP : Transmission Control protocol 신뢰성↑

- UDP : User Datagram Protocol 신뢰성↓

- T-TDU? segment ( 데이터를 적절하게 분할 )

 

5) Network (네트워크)

 

router 기능, packet을 순서대로 전달.

packet을 해당 "목적지"까지 전달. 정확한 목적지냐가 목적

 

- TCP/IP

- N-TDU? packet ( <소스ip> segment <목적ip> )

 

6) Data link (데이터링크)

 

Network Layer의 packet을 오류검사하여 bit 모임인 frame 단위로 만든다.

 

- Ethernet protocol : 각 컴퓨터가 갖고 있는 고유의 MAC (Media Access Control) address(48비트)

- D-TDU? frame

 

7) Physical (물리)

 

twist cable, 전압 등 체크

- P-TDU? bit

 

- PDU의 변화 : data x3 - segment - packet - frame - bit

 


 

□ DNS (Domain Name Server(System))

 

http://www.naver.com => http://128.89.45.73

 

□ NIC (Network Information Center)

 

            apNIC      ripe      interNIC
             /   \
        krnic      jpnic

 

□ IP Address

 

특히 네트워크에서 컴퓨터를 구분하기 위한 컴퓨터 고유주소

32비트, 0~255 사이의 10진수 4개, 구분자는 .(점)이다. ex) 0.0.0.0 부터 255.255.255.255 (IPv4)

 

여기서 내 컴퓨터의 주소는 127.0.0.1 or localhosst or 192.168.34.1

- cmd 켜서 ipconfig /all 치면 검색 가능

IPv4인 경우는 약 40억여개의 주소 사용가능 (IPv6은 128비트)

 

□ Port No

 

한 컴퓨터 내에서 프로세스 구분번호

- 주소 : 포트번호 ex) 198.1.23.22:5678

- 16비트 (65536개 사용가능)

- 사용가능 숫자 중 앞 번호들은 특정 번호에 사용 ex) 20, 21(FTP), 23(telnet), 80(http), ...

 

WYSIWYG : What You See Is What You Get. (위지윅)

 

(참고) ICANN이 나눈 포트번호 범위 : : ICANN은 국제인터넷 주소관리기구로

Internet Corporation for Assigned Names and Numbers의 약어이다.

 

0 ~ 1023 : ICANN이 관리
1024 ~ 49151 : Registered Port라고 하나 ( 관리 제한 없음)
49152 ~ 65535 : Dynamic Port로 사용 가능
(short -32768 ~ +32767 -> 0 ~ 65535)

 

□ Internet 

 

OSI 7 => 4단계

A + P + S => Application

Transport => 그대로 Transport (TCP, 신뢰성 전달을 위해 패킷나눔 및 조립실시)

Network => 그대로 Network (IP , 정확한 목적지로 전송)

D + P => NetworkInterface

 

□ Thread

 

1) Program 

 

예를 들어 메모장이라면 메모장 실행파일이 '보조기억장치 디스크' 등에 들어있는 상태

윈도우 + R notepad.exe (메모장 실행파일)

매번 이런식으로 메모장을 열면 불편하므로 꺼내는 아이콘을 만들어서 실행한다.

 

2) Process

 

메모장 파일 등이 디스크에서 실행되어 메모리에 올라온 상태

 

3) Thread (-> TSS : Time Sharing System)

 


 

■ 스레드 - 1

 

package day06_1;


class ThreadClass extends Thread {
	public void run() {
		System.out.println("스레드와 오늘부터 1일");
	}
}

public class Thread1 {

	public static void main(String[] args) {
		ThreadClass tc1 = new ThreadClass();
		
		tc1.start();
		System.out.println("나는 메인");

	}

}

 

<결과>

나는 메인
스레드와 오늘부터 1일

 

■ 스레드 - 2

 

package day06_1;

class ThreadClass2 extends Thread{
	public void run() {
		for(int i=0; i<5; i++) {
			System.out.println(getName() + "내가 쏘고 있음");
			
			try {
				Thread.sleep(500); // 500ms = 0.5초
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class ThreadClass3 extends Thread{
	public void run() {
		for(int i=0; i<5; i++) {
			System.out.println(getName() + "네가 쏘는 거야?");
			
			try {
				Thread.sleep(1000); // 1초
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

public class Thread2 {

	public static void main(String[] args) {
		
		ThreadClass2 tc2 = new ThreadClass2();
		ThreadClass3 tc3 = new ThreadClass3();
		
		tc2.start();
		tc3.start();

	}

}

 

■ 스레드 - 3

 

package review.jav;

/*
 * 무인마트에서 물품을 집어 카트에 놓으면 "구입"으로 처리되고
 * 다시 물품을 카트에서 빼 진열대에 높으면 "구입취소"로 처리된다.
 * 또한 이 과정은 고객이 GATE를 들어올 때 시작하여 고객이 GATE를 나가면서 결제처리 된다.
 * 
 * 이를 처리할 수 있는 스레드 프로그램을 작성하시오
 * 예) 우리도 아마존 고~
 * 1st 고객 gate 통과
 * 2nd 고객 gate 통과
 * 
 * 홍길동님 구입 +++++ 물품 : 비누 구입가격 : 2000
 *  :
 * 성춘향님 구입 +++++ 물품 : 우산 구입가격 : 7500
 *  :
 * 홍길동님 구입 +++++ 물품 : 수건 구입가격 : 5000
 * 
 * 성춘향님 총 구입금액 13500원입니다.
 * 2nd 고객 Gate 나가면서 결제완료.
 * 
 * 홍길동님 취소 ----- 물품 : 수건 취소가격 : 5000
 * 홍길동님 총 구입금액 33500원입니다.
 * 1st 고객 Gate 나가면서 결제완료. 
 * 
 * <참고>
 * 물품을 장바구니에 넣으면 구입처리, 다시 꺼내 놓으면 취소처리
 * 고객이 gate out하면 결제
 * 
 * */

//RFID becon

class Mart{
	private String customer; // 고객명
	private String moolpoom; // 물품이름
	private int price; // 물품가격
	private int tot; // 총구매금액
	
	public Mart() {
		
	}
	
	public Mart(String customer) { // 생성자 - 고객이름
		super();
		this.customer = customer;
	}
	
	public String getCustomer() {
		return customer;
	}
	public void setCustomer(String customer) {
		this.customer = customer;
	}
	public String getMoolpoom() {
		return moolpoom;
	}
	public void setMoolpoom(String moolpoom) {
		this.moolpoom = moolpoom;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	
	public void kooib(String moolpoom, int price) {
		this.moolpoom = moolpoom;
		this.price = price;
		tot = tot + price;
		System.out.println(customer + "님 구입 +++++ 물품 : " + getMoolpoom() + " 구입가격 : "
				+ getPrice());
		
	}
	
	public void chiso(String moolpoom, int price) {
		this.moolpoom = moolpoom;
		this.price = price;
		tot = tot - price;
		System.out.println(customer + "님 취소 ----- 물품 : " + getMoolpoom() + " 취소가격 : "
				+ getPrice());
	}
	
	public String toString() {
		return customer + "님의 총 구입금액 " + tot + "원입니다.";
	}
} // end Mart class

class MartClass1 extends Thread{
	
	public void run() {
		System.out.println("1st 고객 Gate 통과");
		Mart mart1 = new Mart("홍길동");
		mart1.kooib("카메라", 500000);
		mart1.kooib("청바지", 32000); 
		mart1.kooib("과자", 1500);
		mart1.chiso("카메라", 500000);
		System.out.println(mart1); // mart1.toString();
		System.out.println("1st 고객 Gate 나가면서 결제완료");
	}
}

class MartClass2 extends Thread{
	
	public void run() {
		System.out.println("2nd 고객 Gate 통과");
		Mart mart2 = new Mart("성춘향");
		mart2.kooib("비누", 2000); 
		mart2.kooib("수건", 5000); 
		mart2.kooib("우산", 7500);
		mart2.chiso("비누", 1000);
		System.out.println(mart2); // mart2.toString();
		System.out.println("2nd 고객 Gate 나가면서 결제완료");
	}
}

public class ThreadBank {

	public static void main(String[] args) {
		
		System.out.println("이것 잘하면 아마존고가 오라 할지 몰라?!");
		MartClass1 th1 = new MartClass1();
		MartClass2 th2 = new MartClass2();
		th1.start();
		th2.start();

	}

}

/*
 * 이렇게 스레드를 상속을 해서 사용하는 경우에는 이미 thread를 상속했기 때문에 추가적인 상속이 불가능하다.
 * 그래서 인터페이스(implements)를 이용한다. 
 * */

 

/*
 * Thread를 처리하는 2가지 방법
 * 
 * 1) extends thread : simple, 확장성 x (다중상속 인정을 x)
 * 2) implements Runnable : 인터페이스, 확장성 o, 상속 o (다른 인터페이스, 기본 상속도 가능)
 * 
 * 클래스명 뒤에 implements Runnable 
 * 그렇다고 해서 클래스 이름이 반드시 RunnableClass일 필요는 x
 * 
 * */

 

■ Runnable - 1

 

package review.jav;

/*
 * Thread를 처리하는 2가지 방법
 * 
 * 1) extends thread : simple, 확장성 x (다중상속 인정을 x)
 * 2) implements Runnable : 인터페이스, 확장성 o, 상속 o (다른 인터페이스, 기본 상속도 가능)
 * 
 * 클래스명 뒤에 implements Runnable 
 * 그렇다고 해서 클래스 이름이 반드시 RunnableClass일 필요는 x
 * 
 * */

class RunnableClass implements Runnable{ // Thread 선언이 된 것

	@Override
	public void run() {
		System.out.println("Thread와 오늘부터 1일");
	}
}

public class TRunnable {

	public static void main(String[] args) {
		// (1)
		RunnableClass rc1 = new RunnableClass();
		Thread th1 = new Thread(rc1); // + 스레드로 // extends Thread
		
		// (2) 위 두 줄을 한 줄로 작성하려면
		// Thread th1 = new Thread(new RunnableClass());
		
		th1.start();
	}

}

 

■ Runnable - 2

 

package review.jav;


class RunnableClass1 implements Runnable{ // Thread 선언

	@Override
	public void run() {
		for(int i=1; i<=10; i++) { // 앞에서는 이름없이 getName()을 출력하라고 하니 thread-0,1로 출력됨.
			Thread.currentThread().setName("나는 무적의 ");
			System.out.println(Thread.currentThread().getName() + "내가 쏘고 있네");
			
			try {
				Thread.sleep(100);
			} catch(InterruptedException e) {
				// e.printStackTrace();
			}
		}
		
	} 
	
}

class RunnableClass2 implements Runnable{ // Thread 선언

	@Override
	public void run() {	
		for(int i=1; i<=10; i++) { // 앞에서는 이름없이 getName()을 출력하라고 하니 thread-0,1로 출력됨.
			Thread.currentThread().setName("나는 최고~ ");
			System.out.println(Thread.currentThread().getName() + "네가 쏘는 건가");
			
			try {
				Thread.sleep(100);
			} catch(InterruptedException e) {
				// e.printStackTrace();
			}
		} // end for
	} // end run
} // end RunnableClass2
public class TRunnable_2 {

	public static void main(String[] args) {
		
		Thread th1 = new Thread(new RunnableClass1()); // 두 줄을 한 줄로 줄여쓰는 기법 사용
		Thread th2 = new Thread(new RunnableClass2());
		th1.start();
		th2.start();

	}

}

 

■ Runnable - 3

 

package review.jav;

class RunnableClass3 implements Runnable{

	String moya;
	
	public RunnableClass3(String moya) {
		this.moya = moya;
	}
	
	@Override
	public void run() {
		for (int i=1; i<=10; i++) {
			System.out.println(i + "번" + moya);
			
			try {
				Thread.sleep((int)Math.ceil(Math.random()*2000));
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		} // end for
	} // end run
	
}

class RunnableClass4 implements Runnable{

	String moya;
	
	public RunnableClass4(String moya) {
		this.moya = moya;
	}
	
	@Override
	public void run() {
		for (int i=1; i<=10; i++) {
			System.out.println(i + "번" + moya);
			
			try {
				Thread.sleep((int)Math.ceil(Math.random()*2000));
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		} // end for
	} // end run
	
}

public class Runnable_Thread {

	public static void main(String[] args) {
		Thread th1 = new Thread(new RunnableClass3("사랑한다"));
		Thread th2 = new Thread(new RunnableClass4("아니다 썸이다-"));
		th1.start();
		th2.start();
		System.out.println("그냥 넣어봤어");
	}
}

 

■ Thread / Runnable 

 

package day07_5;

// 이번엔 하나를 스레드, 하나는 Runnable로?

class ThreadClass extends Thread{ // extends Thread

	@Override
	public void run() {	
		for(int i=1; i<=10; i++) {
			System.out.println("백화점 가자");
			try {
				Thread.sleep(100);
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		} // end for
	} // end run
}

class RunnableClass implements Runnable{ // implements Runnable

	@Override
	public void run() {	
		for(int i=1; i<=10; i++) {
			System.out.println("마트 가자");
			try {
				Thread.sleep(100);
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		} // end for
	} // end run
}

public class B01_runnable2 {
	
	public static void main(String[] args) {
		
		ThreadClass th1 = new ThreadClass(); 
		// (1) extends Thread 때문에 Thread 포함이므로 new만 하면 된다. (Thread + new)
		Thread th2 = new Thread(new RunnableClass()); 
		// (2) implements Runnable 이므로 RunnableClass에 대한 객체에다 Thread를 포함해야 함. (new + Thread)
		th1.start();
		th2.start();
	}

}

 

■ Thread_Stop

 

/*
 * 1) interrupt() 방식
 * 2) flag-stop 방식은 CPU에 부하가 많이 걸리므로 권장은 아님
 *   
 * */

 

package review.jav;

/*
 * 1) interrupt() 방식
 * 2) flag-stop 방식은 CPU에 부하가 많이 걸리므로 권장은 아님
 *   
 * */

class RunnableClass implements Runnable{

	@Override
	public void run() {
		while(true) { // 무한루프
			System.out.println("무한루프 스레드!");
			if(Thread.interrupted()) // 너 한번 나 한번 하다가
				break;
		} // while - end
		System.out.println("***5초후에 종료된 것임***");
	}	
}

public class ThreadStop {

	public static void main(String[] args) throws InterruptedException {
		// 스레드는 기다려주지 않는다.
		// start() 함수 밑에 print() 함수가 있다면 print 함수가 먼저 실행된다.
		
		Thread th1 = new Thread(new RunnableClass());
		th1.start();
		Thread.sleep(5000); // 5초
		th1.interrupt(); // 전에는 stop => deprecated
		// error 처리를 하고 싶으면 try-catch가 필요하다.
		// throw는 던지는 것
		// throws는 re-throw 
	}

}

 

728x90
반응형

'IT&코딩 > 국비지원' 카테고리의 다른 글

SQL - 2  (0) 2023.04.13
SQL - 1  (0) 2023.04.13
네트워크 - 2 (네트워크)  (0) 2023.03.23
Java - 2  (0) 2023.03.22
Java - 1  (0) 2023.03.20