1~5. 다음 코드에 대한 출력 결과를 쓰시오.
1.
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> System.out.println("Hello from thread"));
thread.start();
}
}
2.
public class Main {
public static void main(String[] args) {
Runnable task = () -> System.out.println("Running in a thread");
Thread thread = new Thread(task);
thread.start();
}
}
3.
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(counter::increment);
Thread t2 = new Thread(counter::increment);
t1.start();
t2.start();
}
}
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
System.out.println(count);
}
}
4.
public class Main {
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(() -> {
synchronized(lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 resumed");
}
});
Thread t2 = new Thread(() -> {
synchronized(lock) {
lock.notify();
System.out.println("Thread 2 completed");
}
});
t1.start();
t2.start();
}
}
5.
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new Task("Task 1"));
Thread t2 = new Thread(new Task("Task 2"));
t1.start();
t2.start();
}
}
class Task implements Runnable {
private String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(name + ": " + i);
}
}
}
정답
(드래그 시 정답이 보입니다.)
1. Hello from thread
2. Running in a thread
3. 1
2
4. Thread 2 completed
Thread 1 resumed
5. Task 1: 0
Task 1: 1
Task 1: 2
Task 2: 0
Task 2: 1
Task 2: 2
'Study > 정보처리기사' 카테고리의 다른 글
| JAVA Level 9 (0) | 2025.02.21 |
|---|---|
| JAVA Level 8 (0) | 2025.02.21 |
| JAVA Level 7 (0) | 2025.02.21 |
| JAVA Level 6 (0) | 2025.02.21 |
| JAVA Level 5 (0) | 2025.02.21 |