问答题
阅读以下说明和Java代码,将应填入(n)处的字句写在对应栏内。
【说明】
下面的Java程序演示了程序竞争资源(Mutex的实例对象)而引起程序死锁的一种例子。
【Java程序】
import java.applet.*;
import java.awt.*;
//此处声明一个互斥类
class Mutex { }
class A extends {{U}}(1) {{/U}}
{
private Mutex first,second;
public A(Mutex f,Mutex s)
{
first = f;
second = s;
}
public void run()
{
//锁定first变量
{{U}} (2) {{/U}} (first)
{
try
{ //本线程挂起,等待重新调度
Thread.sleep(1); //注意此处(1)不是小题序号
}
catch(InterruptedException e){}
System. out. println("threadA got first mutex");
{{U}} (2) {{/U}} (second) //锁定second变量
{ //do something
System. out. println("threadA got second mutex");
} //释放second变量
} //释放first变量
}
}
class B extends{{U}} (1) {{/U}}
{
private Mutex first,second;
public B(Mutex f,Mutex s)
{
{{U}} (3) {{/U}};
second = s;
}
public void run()
{
{{U}} (2) {{/U}} (second) //锁定second变量
{
//do something
try
{
Thread.sleep(((int)(3*Math.random()))*1000);
//本线程挂起,等待重新调度
}
catch(InterruptedException e){}
System.out.println("threadB got second mutex");
{{U}} (2) {{/U}} (first) //锁定first变量
{
//do something
System.out.println("threadB got first mutex");
} //释放first变量
} //释放second变量
}
}
public class DeadlockExample
{
public static void main(String arg[])
{
Mutex mutexX = new Mutex();
Mutex mutexY = new Mutex();
AthreadA = new A(mutexX,mutexY);
B threadB = new B{{U}} (4) {{/U}};
threadA.{{U}} (5) {{/U}};
threadB.start();
}
}
问答题
【正确答案】
【答案解析】
问答题
【正确答案】
【答案解析】synchronized [解析] 使用同步关键字synchronized锁定互斥变量。
问答题
【正确答案】
【答案解析】first = f [解析] 将本类的私有变量first指向调用的实参变量f。
问答题
【正确答案】
【答案解析】mutexX,mutexY [解析] 为演示信号量互斥,对象threadA和threadB需要使用相同的互斥信号量。
问答题
【正确答案】
【答案解析】start() [解析] 开始线程threadA。