我正在为 SCJP 做准备,而多线程一直是我最不稳定的领域,主要是因为我不知道如何查看多线程代码并遍历它。到目前为止,我的方法一直是用英语写下每个线程中可能发生的情况,并测试一些线程随机交叉的情况,这是一种非常偶然且耗时的方法。所以我想看看专业人士会怎么做。您是否愿意阅读下面的代码(这是给我带来麻烦的最新问题)并在计算可能的输出时写下您的想法(仅与代码相关的内容,请:)?问题附带的选择在最后。我正在寻找的不是我拥有的解决方案,而是一个人如何在考试中有效地得出解决方案。
是的,我知道这个问题没有准确的答案,等等。接受的投票是最清晰和最容易模仿的答案,好的 :)
谢谢大家!
问题:这些答案中哪些是可能的输出?
public class Threads1 {
int x = 0;
class Runner implements Runnable {
public void run() {
int current = 0;
for (int i = 0; i < 4; i++) {
current = x;
System.out.print(current + ", ");
x = current + 2;
}
}
}
public static void main(String[] args) {
new Threads1().go();
}
public void go() {
Runnable r1 = new Runner();
new Thread(r1).start();
new Thread(r1).start();
}
}
选择(选择所有适用项):
一个。 0, 2, 4, 4, 6, 8, 10, 6,
B. 0, 2, 4, 6, 8, 10, 2, 4,
C. 0, 2, 4, 6, 8, 10, 12, 14,
D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
E. 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,
最佳答案
A 和 C(假设问题是这些答案中哪些是可能的输出?)
当然,困难的部分不在于找到可能的解决方案。而是,认真审视那些您认为不可能可能的事情,并努力说服自己您有充分的理由并且您已经排除了所有绕过你的理由的方法。
So far my approach has been to write down in English what might be happening in each thread ...
您需要弄清楚哪个线程打印了每个数字。下面是我能想到的最有效、最简洁的格式,可以让您在处理各种可能性时轻松划掉/删除/改写。实现:
找到可能的答案后继续。不管它在现实世界中是不可能的还是可能存在其他可能(或不可能)的组合都没有关系。只要找到 1 种可能性,您就可以继续。
首先尝试最简单的方法,例如为每个数字假设 T1,直到你找到一个不可能是 T1 的数字,所以你填写 T2,依此类推。希望你在没有矛盾(或容易解决的矛盾)的情况下结束。找到可能的组合后,继续。
随意跳转以快速消除可能的,这样您就可以专注于可能不可能的。
这是我的草稿纸/工作表的最终编辑(附有我的心理注释):
A. 0, 2, 4, 4, 6, 8, 10, 6,
1 1 1 2 2 2 2 1 <- possible threads that produced this output - possible solution
B. 0, 2, 4, 6, 8, 10, 2, 4,
1 2 2 2 2 ? 1 <- to print second '2', T1 interrupted between L10/L11; 4 passes of T2 used up
C. 0, 2, 4, 6, 8, 10, 12, 14,
1 1 1 1 2 2 2 2 <- possible solution - simplest solution (T2 waits until T1 is completely done) - doesn't matter that it isn't likely, just that is possible
D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
1 2 1 2 1 2 1 2 1 2 ? <- threads used up
E. 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,
1 1 1 1 2 2 2 2 ? <- threads used up
注意:
http://download.oracle.com/javase/tutorial/essential/concurrency/atomic.html
- Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
- ...
Atomic actions cannot be interleaved, so they can be used without fear of thread interference.
关于java - 您如何思考和预测这样的线程问题的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3800146/