Thread Class Exercise

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

1.

Study the Java program given below. Line numbers have been included so that you can refer
to them in your answer if you wish.
1. class Car {
2.
public void steerCar() {
3.
for (int i = 0; i < 5; i++) {
4.
if (i % 2 == 0) { // true if i is 0 or an even number
5.
System.out.println(Thread.currentThread().getName() + " steers left");
6.
} else {
7.
System.out.println(Thread.currentThread().getName() + " steers right");
8.
}
9.
try {
10.
Thread.sleep(10);
11.
} catch (InterruptedException ex) { }
12.
}
13. }
14. }
15. class Driver extends Thread {
16. private Car car;
17. public Driver(String name, Car car) {
18.
this.car = car;
19.
setName(name); // set the name of the Thread
20. }
21. public void run() {
22.
car.steerCar();
23. }
24. }
25. public class ThreadClassExercise {
26. public static void main(String[] args) {
27.
System.out.println("*** driving lesson starts ***");
28.
Car car = new Car();
29.
Driver learner = new Driver("Lev", car);
30.
Driver instructor = new Driver("Irina", car);
31.
learner.start();
32.
instructor.start();
33.
System.out.println("*** driving lesson ends ***");
34. }
35. }

(a)

Give sample output that the program could produce when run. Comment on the
output in detail and identify ways in which the output may differ from that which you
give.

(b)

Explain the purpose of the keyword synchronized in Java. Illustrate your answer by
discussing what would happen if it were added to the declaration of the method
steerCar() in the code above.

You might also like