Java Threads: Are there any results that CANNOT be the output of these programs? (code given)
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);开发者_Python百科
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();
}
}
The key point is the synchronized keyword in the method signature. That's why you always have the two letters consecutively in the first (e.g. cc
). Without that (the second), the only constraint is that a
and b
are printed exactly twice (in some order), and no other characters are printed.
Running the program is not that helpful for testing threading. You have to demonstrate why it's correct.
Matthew is right for the first. So it can have anything like aabbcc or ccbbaa as long as it is consecutive, hence the synchronized
term.
The second one I think the code wont print out aacc. Tell me if I am wrong
精彩评论