What is the output of the following Java Snippet:
public class MyParallelClass implements java.lang.Runnable {
public String name;
public myParallelTry(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name);
}
}
public class test {
public static void main(String[] args) {
MyParallelClass a = new MyParallelClass("A");
MyParallelClass b = new MyParallelClass("B");
MyParallelClass c = new MyParallelClass("C");
MyParallelClass d = new MyParallelClass("D");
new Thread(a).start();
new Thread(b).start();
new Thread(c).start();
new Thread(d).start();
System.out.println("-");
new Thread(a).start();
new Thread(b).start();
new Thread(c).start();
new Thread(d).start();
System.out.println("-");
new Thread(a).start();
new Thread(b).start();
new Thread(c).start();
new Thread(d).start();
System.out.println("-");
new Thread(a).start();
new Thread(b).start();
new Thread(c).start();
new Thread(d).start();
}
}
. . . . . . . . . . . . . . . . . . . . . . .
Answer
First Try | Second Try | Third Try |
---|---|---|
|
|
|
Explanation
If you start threads like this, you don't get any guarantee that they will finish their execution in order. If you want them to execute in block of four, you could use join():
public class test {
public static void main(String[] args) {
myParallelTry a = new myParallelTry("A");
myParallelTry b = new myParallelTry("B");
myParallelTry c = new myParallelTry("C");
myParallelTry d = new myParallelTry("D");
Thread tA = new Thread(a); tA.start();
Thread tB = new Thread(b); tB.start();
Thread tC = new Thread(c); tC.start();
Thread tD = new Thread(d); tD.start();
try {
tA.join();
tB.join();
tC.join();
tD.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-");
tA = new Thread(a); tA.start();
tB = new Thread(b); tB.start();
tC = new Thread(c); tC.start();
tD = new Thread(d); tD.start();
try {
tA.join();
tB.join();
tC.join();
tD.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-");
tA = new Thread(a); tA.start();
tB = new Thread(b); tB.start();
tC = new Thread(c); tC.start();
tD = new Thread(d); tD.start();
try {
tA.join();
tB.join();
tC.join();
tD.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-");
tA = new Thread(a); tA.start();
tB = new Thread(b); tB.start();
tC = new Thread(c); tC.start();
tD = new Thread(d); tD.start();
try {
tA.join();
tB.join();
tC.join();
tD.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
First Try | Second Try | Third Try |
---|---|---|
|
|
|