프로세스는 프로그램을 실행시켜서 메모리에 올라가있는 상태이다.
쓰레드는
“프로세스 내에서 실행되는 여러 흐름의 단위”
"프로세스의 특정한 수행 경로"
"프로세스가 할당받은 자원을 이용하는 실행의 단위"로
표현 할 수있다.
스레드에서 동기화란 synchronized 키워드를 사용해,
여러개의 스레드가 한개의 자원을 사용하고자 할 때,
현재 데이터를 사용하고 있는 해당 스레드를 제외하고 나머지 스레드들은 데이터에 접근 할 수 없도록 막는 개념이다.
10 9 8 7 6 ... 이 1초마다 실행 되도록 쓰레드를 완성하시오.
public static void main(){
ThreadCount threadCount = new ThreadCount();
threadCount.start();
String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
System.out.println("입력하신 값은 " + input + "입니다.");
}
class ThreadCount {
public void run () {
for(int i=10; i>0; i--) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
}catch(IOException e){
e.printStackTrace();
}
}
}
IO 스트림이란 InputStream과 OutputStream을 뜻하며,
데이터와 또 다른 데이터 간의 입력과 출력을 담당하는 가상의 연결고리(stream)이다.
IO 스트림은 단방향으로만 이동이 가능하기때문에 두 방향인 InputStream과 OutputStream이 있는 것이다.
console log
대상 파일: a.java
사본 이름: x:\b.java
파일 복사가 되었습니다.
소스코드
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("대상 파일 : ");
String src = sc.nextLine();
System.out.print("사본 이름 : ");
String dst = sc.nextLine();
try(InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
int data;
while(true) {
data = in.read();
if(data == -1)
break;
out.write(data);
}
}
catch(IOException e) {
e.printStackTrace();
}
System.out.println("파일 복사가 되었습니다.");
}
try에 자원 객체를 전달하면, try 코드 블록이 끝나면 자동으로 자원을 종료해주는 기능이다.
즉, 따로 finally 블록이나 모든 catch 블록에 종료 처리를 하지 않아도 되게 된다.
class Account {
private int balance = 1000;
public int getBalance() {
return balance;
}
public void withdraw(int money) throws InterruptedException{
if(balance >= money) {
//try {
Thread.sleep(1000);
//} catch(InterruptedException e) {}
balance -= money;
}
} // withdraw
}
class RunnableEx21 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;
try {
acc.withdraw(money);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("balance:"+acc.getBalance());
}
} // run()
}
class ThreadEx21 {
public static void main(String args[]) {
Runnable r = new RunnableEx21();
new Thread(r).start();
new Thread(r).start();
}
}
여러 스레드들이 서로 동시에 접근해서
서로 메소드가 끝나지도 않았음에도 불구하고 중간에 sleep(1000)을 실행해서 스레드가 쉬고 있는 동안, 다른 스레드가 접근해서 또 연산이 이루어졌기 때문에 sleep(1000)이 끝난 뒤 연산이 마무리되어 음수값이 반환된다.
synchronized 키워드를 사용하면 한꺼번에 한 스레드만 접근이 가능하기 때문에 한 스레드에서의 sleep(n)과 관계없이, 메소드의 모든 연산이 끝난 후에 다음 스레드의 접근이 허용되게 해 음수값이 반환되지 않게 할 수 있다.
다만 synchronized 키워드를 빈번하게 사용하게 된다면, 한꺼번에 하나의 스레드만 데이터에 접근이 가능하기때문에, 프로세스의 실행속도가 느려질 수 있다.