Nextlabs Interview Question
4 Interview Reviews |
Back to all Nextlabs Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Java Engineer at Nextlabs:
5. The user of this class expected the output “Num: 1000000”. They got something else. What went wrong and how would you fix it? public class Test { public final static int NUMTHREADS = 1000; public final static int NUMLOOP = 1000; public static int num = 0; static class Mythread extends Thread { @Override public void run() { for (int i = 0; i < NUMLOOP; i++) { ++num; } } } public static void main(String argv[]) { Mythread threads[] = new Mythread[NUMTHREADS]; for (int i = 0; i < NUMTHREADS; ++i) { threads[i] = new Mythread(); threads[i].start(); } try { for (int i = 0; i < NUMTHREADS; ++i) { threads[i].join(); } } catch (InterruptedException e) { } System.out.println("Num: " + num); } }
| Tags: | java, thread See more , See less 8 |
Helpful Question?
Yes |
No
Inappropriate?
0 of 0 people found this helpful
by Interview Candidate:
public final static int NUMTHREADS = 1000;
public final static int NUMLOOP = 1000;
public static int num = 0;
static class Mythread extends Thread{
@Override
public void run(){
for (int i = 0; i < NUMLOOP; i++){
add();
}
}
private synchronized static void add(){
++num;
}
}
public static void main(String argv[]){
Mythread threads[] = new Mythread[NUMTHREADS];
for (int i = 0; i < NUMTHREADS; ++i){
threads[i] = new Mythread();
threads[i].start();
}
try{
for (int i = 0; i < NUMTHREADS; ++i){
threads[i].join();
}
}catch (InterruptedException e){}
System.out.println("Num: " + num);
}
}