Read the following code and try to guess what will be its output. import java.util.*; class Car { private int speed; public void setSpeed(int s){ this.speed=s; } public int getSpeed(){ return speed; } } class ChangeSpeedCar extends Thread{ Car car; int step; public ChangeSpeedCar(Car obj,String s,int a){ super(s); this.step=a; this.car=obj; } public void run(){ for(int i=0;i<10000;i++) { int c=car.getSpeed(); c+=step; car.setSpeed(c);} }} public class test { public static void main(String[]args){ Car obj =new Car(); obj.setSpeed(0); ChangeSpeedCar Th1 = new ChangeSpeedCar(obj , "MyThread1",1); ChangeSpeedCar Th2 = new ChangeSpeedCar(obj , "MyThread2",-1); Th1.start(); Th2.start(); try{ Thread.sleep(1000); }catch(Exception e){System.out.print("Error");} System.out.println("The speed of the car is "+obj.getSpeed());}}Output:
Exercise 1:
1) Read the following code and try to guess what will be its output. import java.util.*;
class Car { private int speed;
public void setSpeed(int s){ this.speed=s; } public int getSpeed(){ return speed; } } class ChangeSpeedCar extends Thread{
Car car; int step;
public ChangeSpeedCar(Car obj,String s,int a){ super(s);
this.step=a;
this.car=obj; }
public void run(){ for(int i=0;i<10000;i++) { int c=car.getSpeed(); c+=step;
car.setSpeed(c);} }}
public class test {
public static void main(String[]args){ Car obj =new Car();
obj.setSpeed(0);
ChangeSpeedCar Th1 = new ChangeSpeedCar(obj , "MyThread1",1); ChangeSpeedCar Th2 = new ChangeSpeedCar(obj , "MyThread2",-1); Th1.start(); Th2.start();
try{
Thread.sleep(1000);
}catch(Exception e){System.out.print("Error");}
System.out.println("The speed of the car is "+obj.getSpeed());}}Output:
2) Write the code and execute it many times. Is the output similar to your previous answer? What’s the issue? How can you modify the code to obtain the expected output? Modify the code and execute it
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 2 images