线程我刚入手,红色部分为我自己的答案,希望各位指教。谢谢...Given the following code, which statements concerning the objects referenced through the member variables i, j and k are true, given that any thread may call the methods a, b and c at any time?class Counter {
int v = 0; synchronized void inc() { v++; } synchronized void dec() { v--; }}public class Q7ed5 { Counter i; Counter j; Counter k; public synchronized void a() { i.inc(); System.out.println("a"); i.dec(); } public synchronized void b() { i.inc(); j.inc(); k.inc(); System.out.println("b"); i.dec(); j.dec(); k.dec(); } public void c() { k.inc(); System.out.println("c"); k.dec(); }}
[Select All]
[1]i.v is guaranteed always to be 0 or 1.//true[2]j.v is guaranteed always to be 0 or 1.//true[3]k.v is guaranteed always to be 0 or 1 //false[4]j.v will always be greater than or equal to k.v at any give time.//true,理由同[5][5]k.v will always be greater than or equal to j.v at any give time.//false,因为方法b里是先j.inc()后k.inc();
int v = 0; synchronized void inc() { v++; } synchronized void dec() { v--; }}public class Q7ed5 { Counter i; Counter j; Counter k; public synchronized void a() { i.inc(); System.out.println("a"); i.dec(); } public synchronized void b() { i.inc(); j.inc(); k.inc(); System.out.println("b"); i.dec(); j.dec(); k.dec(); } public void c() { k.inc(); System.out.println("c"); k.dec(); }}
[Select All]
[1]i.v is guaranteed always to be 0 or 1.//true[2]j.v is guaranteed always to be 0 or 1.//true[3]k.v is guaranteed always to be 0 or 1 //false[4]j.v will always be greater than or equal to k.v at any give time.//true,理由同[5][5]k.v will always be greater than or equal to j.v at any give time.//false,因为方法b里是先j.inc()后k.inc();
3 应该也是错误的 假设线程 A,B
A在访问了C方法的K.INC以后么有访问K.DEC以前 B访问了B方法并且在A线程中执行K.DEC之之前执行了K.INC那么K的值就为2随后才变为 1 0
2.true
3.false
4.false
5.true
1)true 因为i只在a()与b()中出现
2)true 因为i只在b()中出现
3)false 因为可能:先b()中的k.inc(),接着是c中的k.inc(),此时k.v=2了
4)false 因为可能:先c()中的k.inc(),此时k.v>j.v
5)false 因为可能:先b()中的j.inc(),此时j.v>j.v
比如下面这个
只有当接到notify()才执行bFull下面的语句么
while(你的条件不满足){
wait();
}
所以在某个同一时刻线程方法a和b可能会被2个不同的线程同时调用
又因为在方法a和b里都有调用到i.inc
这时可能有的人会问可是inc方法是synchronized
没错i.inc方法也是synchronized但它只能保证每个线程的i.inc方法不能同时调用
却不能保证i.inc方法调用后在调用i.dec方法后才能再一次调用i.inc方法
所以有可能在线程A里调用了i.inc方法后线程B里在线程A里的i.dec方法调用前就调用了i.inc方法
这时i.v的值就会是2,所以i.v还有一个可能值是2
其他的同理