I had a quiz for Threads last week and I got these 2 questions wrong. I was wondering if anyone can help me get the right answer for these. Thanks.
Are there any results that CANNOT be the output of this program?
I get confused with these sort of questions. I ran the program and found that Bbccaa is possible, aaccbb is possible, ccbbaa is possible and aabbcc is possible.
public class Test4 extends Thread { //8
public Test4(String name) {
super(name);
}
public void run() {
print(getName());
}
public static synchronized void print(String n) {
System.out.print(n);
try { sleep(...); } catch (Exception ex) {} // unspecified random time
System.out.print(n);
}
public static void main(String argv[]) throws Exception {
Test4 ta = new Test4("a");
Test4 tb = new Test4("b");
Test4 tc = new Test4("c");
ta.start();
tb.start();
tc.start();
ta.join();
tb.join();
tc.join();
}
}
Same question for this code
Abab is possible, baab is possible, baba is possible. I get confused with these sort of questions. Is there any tricks or tips that will help me understand which output is not possible.
public class Test3 extends Thread {
public Test3(String name) {
super(name);
}
public void run() {
print(getName());
}
public static void print(String n) {
System.out.print(n);
try { sleep(...); } catch (Exception ex) {}
System.out.print(n);
}
public static void main(String argv[]) throws Exception {
Test3 ta = new Test3("a");
Test3 tb = new Test3("b");
Test3 tc = new Test3("c");
ta.start();
tb.start();
ta.join();
tb.join();
}
}
Matthew is right for the first. So it can have anything like aabbcc or ccbbaa as long as it is consecutive, hence the
synchronizedterm.The second one I think the code wont print out aacc. Tell me if I am wrong