44일차 - 2023.2.27

문우림·2023년 3월 3일
0

Java

목록 보기
23/23

1. Thread(sleep()메소드)

자기자신 쓰레드를 정한 시간동안 멈추고 다른 쓰레드를 context switching한다.

package Thread;
import javax.swing.JOptionPane;

public class ThreadTest {

	public static void main(String[] args) {
		String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
		System.out.println("입력하신 값은 " + input + "입니다.");
		for (int i = 10; i > 0; i--) {
			System.out.println(i);
			try {
				Thread.sleep(1000); // 1초간 시간을 지연한다.
			} catch (Exception e) {
			}
		}
	}

}

Thread(sleep()메소드) 예제

package Thread;

public class Thread2_1 extends Thread{

	@Override
	public void run() {
		for (int i = 10; i > 0; i--) {
			System.out.println(i);
			try {
				Thread.sleep(1000);
			} catch (Exception e) {

			}
		}
	}
}
package Thread;

public class Thread2_2 extends Thread{
	@Override
	public void run() {
		for (int i = 10; i > 0; i--) {
			System.out.println(i);
			try {
				Thread.sleep(3000);
			} catch (Exception e) {

			}
		}
	}
}

main

public class Threadmain {

	public static void main(String[] args) {
		String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
		System.out.println("입력하신 값은 " + input + "입니다.");
		Thread2_1 thd = new Thread2_1();
		Thread2_2 thr = new Thread2_2();
		thd.start();
		thr.start();
      }
        }
  • Thread.sleep(1000);는 약1초 실행을 멈추고, Thread.sleep(3000);은 약3초 실행을 멈춘다. sleep를 통해 실행을 멈추는 동안 각각 쓰래드가 실행된다.

쓰레드 동기화(synchronized)

Thread의 특징은...
복수의 쓰레드가 있는 경우 하나의 쓰레드가 끝나기 전에 다른 쓰레드가 경쟁적으로 치고 들어와서 작업을 실행한다. 서로 번갈아가면서 작업을 수행.

동기화 시키면...
하나의 쓰레드가 끝날 때까지 다른 쓰레드들이 기다려, 하나씩 작업을 수행. 하나의 쓰레드가 종료 후 다른 쓰레드 실행한다.

동기화 예제

package ThreadSynchronization;

public class StringPrint {
	synchronized void display(String s) {
		for(int i = 1; i <= 2; i++) {
			System.out.print(Thread.currentThread().getName() + ":");
			System.out.print(s);
			System.out.println();
		}
		System.out.println();
	}
}

package ThreadSynchronization;

public class PrintThread extends Thread {
	private StringPrint sp;    //new StringPrint(); 
	private String str;

	public PrintThread(String s, StringPrint sp) {
		this.str = s;
		this.sp = sp;
	}

	@Override
	public void run() {
		sp.display(str);
	}
}

main

package ThreadSynchronization;

public class Main {

	public static void main(String[] args) {
		StringPrint sp = new StringPrint();
		
		Thread th1 = new PrintThread("1", sp);
		Thread th2 = new PrintThread("2", sp);
		Thread th3 = new PrintThread("3", sp);
		Thread th4 = new PrintThread("4", sp);
		Thread th5 = new PrintThread("5", sp);
		
		th1.start();
		th2.start();
		th3.start();
		th4.start();
		th5.start();
	}
}

[결과]
Thread-0:1
Thread-0:1

Thread-4:5
Thread-4:5

Thread-3:4
Thread-3:4

Thread-2:3
Thread-2:3

Thread-1:2
Thread-1:2

동기화(syncronized)를 안하면...

[결과]
Thread-0:1
Thread-4:5
Thread-4:5Thread-3:

Thread-2:3
Thread-2:3

Thread-1:2
Thread-1:2
4
Thread-0:1

Thread-3:4

네트워크

내트워크란 다른 장치로 데이터를 이동시킬 수 있는 컴퓨터와
자바의 네트워크 프로그래밍은 TCP/IP 모델.

TCP

TCP(Transmission Control Protocol)는 신뢰할 수 있는 프로토콜로서, 데이터를 상대측까지 제대로 전달되었는지 확인 메시지를 주고 받음으로써 데이터의 송수신 상태를 점검한다.
ex)전화

UDP

UDP(User Datagram Protocol)은 신뢰할 수 없는 프로토콜로서, 데이터를 보내기만하고 확인 메시지를 주고 받지 않기 때문에 제대로 전달했는지 확인하지 않는다.
ex)메일, 편지

InetAddess

InetAddress클래스는 IP주소를 표현한 클래스.
모든 IP주소를 InetAddress를 사용한다.

package com.javalec.networkex;

import java.net.InetAddress;
import java.util.Scanner;

public class InetAdressEx {
	Scanner scanner;

	public InetAdressEx() {
		System.out.println("Host이름을 입력 하세요.");

		scanner = new Scanner(System.in);
		try {
			InetAddress inetAddress = InetAddress.getByName(scanner.next());

			System.out.println("computer NAME : " + inetAddress.getHostName());
			System.out.println("Computer IP : " + inetAddress.getHostAddress());
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

main

package com.javalec.networkex;

public class MainClass {

	public static void main(String[] args) {
		new InetAdressEx();
	}

}
  1. 아래를 실행보고, balance 가 마이너스 금액이 찍히는 이유를 적고
    코드를 수정해 보시오.
class Ex13_12 {
	public static void main(String args[]) {
		Runnable r = new RunnableEx12();
		new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
		new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
	}
}

class Account {
	private int balance = 1000;

	public  int getBalance() {
		return balance;
	}

	public void withdraw(int money){
		if(balance >= money) {
			try { Thread.sleep(1000);} catch(InterruptedException e) {}
			balance -= money;
		}
	} // withdraw
}

class RunnableEx12 implements Runnable {
	Account acc = new Account();

	public void run() {
		while(acc.getBalance() > 0) {
			// 100, 200, 300중의 한 값을 임으로 선택해서 출금(withdraw)
			int money = (int)(Math.random() * 3 + 1) * 100;
			acc.withdraw(money);
			System.out.println("balance:"+acc.getBalance());
		}
	} // run()
}

0개의 댓글