//program 1
class ThreadTest14 extends
Thread {
String name;
public static void main(String[] args) {
new ThreadTest14("first").start();
new ThreadTest14("second").start();
}
ThreadTest14(String s) {
name=s;
}
public void run() {
for (int i=0;i<2;i++) {
System.out.println(name + i);
}
}
}
For program 1, the order of output is uncertain. But no matter what the order is, "first 0" will be the first element, right?
//program 2
class ThreadTest14 extends Thread {
String name;
public static void main(String[] args) {
new ThreadTest14("first").start();
new ThreadTest14("second").start();
}
ThreadTest14(String s) {
name=s;
}
public void run() {
for (int i=0;i<2;i++) {
System.out.println(name + i);
try {
Thread.sleep(1);
}
catch(InterruptedException e) {}
}
}
}
For program 2, I think the uncertainty is avoided by using Thread.sleep()method no matter how short current thread will sleep and the output will always be:
first 0
second 0
first 1
second 1
Am I right? Please help.