멀티쓰레드
public class _04_MultiThread {
public static void main(String[] args) {
Runnable cleaner1 = new Runnable() {
@Override
public void run() {
System.out.println("-- 직원1 청소 시작 --");
for (int i = 1; i <= 10; i += 2) {
System.out.println("(직원1) " + i + "번방 청소 중");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("-- 직원1 청소 끝 --");
}
};
Runnable cleaner2 = () -> {
System.out.println("-- 직원2 청소 시작 --");
for (int i = 2; i <= 10; i += 2) {
System.out.println("(직원2) " + i + "번방 청소 중");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("-- 직원2 청소 끝 --");
};
Thread cleanerThread1 = new Thread(cleaner1);
Thread cleanerThread2 = new Thread(cleaner2);
cleanerThread1.start();
cleanerThread2.start();
}
}
동기화
Room
public class Room {
public int number = 1;
synchronized public void clean(String name) {
// 직원1 : 3번방 청소 중
System.out.println(name + " : " + number + "번방 청소 중");
number++;
}
}
_05_Synchronization
public class _05_Synchronization {
public static void main(String[] args) {
Room room = new Room();
Runnable cleaner1 = new Runnable() {
@Override
public void run() {
System.out.println("-- 직원1 청소 시작 --");
for (int i = 1; i <= 5; i++) {
room.clean("직원1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (i == 2) {
throw new RuntimeException("못해먹겠다!!");
}
}
System.out.println("-- 직원1 청소 끝 --");
}
};
Runnable cleaner2 = () -> {
System.out.println("-- 직원2 청소 시작 --");
for (int i = 1; i <= 5; i++) {
room.clean("직원2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("-- 직원2 청소 끝 --");
};
Thread cleanerThread1 = new Thread(cleaner1);
Thread cleanerThread2 = new Thread(cleaner2);
cleanerThread1.start();
cleanerThread2.start();
}
}
'인강 보습 (인프런,유데미,패스트캠퍼스) > 나도코딩의 자바 기본편' 카테고리의 다른 글
입출력과 파일 (2) (0) | 2023.01.21 |
---|---|
입출력과 파일 (1) (0) | 2023.01.20 |
쓰레드 - (1) Thread, Runnable, Join (0) | 2023.01.19 |
예외처리 (2) - Finally, Try with Resources, 사용자 정의 예외, 예외처리미루기 (0) | 2023.01.19 |
예외처리 - (1) Try Catch , Catch구문, Throw, (0) | 2023.01.19 |