问题 问答题

下面程序是一个计时器,从1000秒开始倒计时,直到为0结束。在界面上有两个按钮,一个可以暂停计时,另一个可以继续已经暂停的计时。请更正题中带下划线的部分。
注意:不改动程序的结构,不得增行或删行
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Example3_4 extends Applet

public Color color = Color.red;
private int num= 1000;
public Counter theCounter;
private Button stop;
private Button start;
public void init()

stop = new Button("暂停");
start = new Button ("继续");
theCounter = new Counter(this);
stop.addActionListener(new Lst() implements ActionListener
public void actionPerformed(ActionEvent e)

theCounter.sus();

);
start.addActionListener(new SuspenListener());
add(start);
add(stop);
theCounter.start();

public void paint(Graphics g)

g.setCotor(color);
g.drawString(String.valueOf(num),50,50);

public void setInt(int i)

num=i;

class SuspenListener implements ActionListener

public void actionPerformed(ActionEvent e)

theCounter.conti ();



public class Counter extends Thread

Example3_4 example;
boolean isHold;
Counter (Example3_4 ex)

this.example = ex;
isHold = false;

public void sus()

isHold = true;

public synchronized void conti()

isHold = false;
notify();

public void run()

for (int i = 1000; i>0; i--)

if (i%2 == 1)
example.color = Color.red;
else
example.color = Color.blue;
example.setInt(i);
example.repaint();
try

sleep(1000);
synchronized
while(isHold)
wait ( );


catch (InterruptedException ie)




<HTML>
<HEAD>
<TITLE>Example3_4</TITLE>
</HEAD>
<BODY>
<applet code="Example3_4.class" width=300 height=400>
</applet>
</BODY>
</HTML>

答案

参考答案:①stop.addActionListener(new ActionListener(){
②class Counter extends Thread
③synchronized(this)

解析: 本程序使用线程类“Counter”来实现计时的功能,该线程的线程体每1000毫秒循环一次,并在每次循环的开始显示剩余的时间。计时器的暂停和继续通过线程的同步与共享来完成,每次循环结束时,判断标志暂停的变量“isHold”是否为真,如果为真则进入挂起状态。当用户按下“暂停”按钮,程序调用Counter类的sus()方法,将变量“isHold”设为真。当用户按下“继续”按钮,程序调用Counter类的conti()方法,将变量“isHold”设为假,并使用notify()取消线程的挂起状态。
本题第1个错误是考查对匿名类的使用。匿名类是Java语言中比较特殊的一种类,这种类不存在类名,而且只能在声明的时候被实例化一次。匿名类必须继承于一个父类或实现一个接口。第1条横线处,原程序打算声明一个新类 Lst实现ActionListener接口,并同时实例化一个新对象。但是只有匿名类才能在声明时创建一个新的类对象。因此此处应改用匿名类实现程序的目的。
第2个错误处考查Java源程序的结构。任何一个“java”文件中有且只有一个被声明为public的类,这个类的名字必须与“java”文件的文件名相同。因此在第2个错误位置处必须去掉 public声明。
synchronized用来定义一个同步块。
synchronized的定义格式是synchronized (expression)statement,expression是对象或类的名字,系统将为该对象设置唯一的锁;statement可以是一个方法定义,也可以是一个语句块,在同一时刻只能有一个线程执行这个块中的操作。因此第3个错误处必须指明同步的对象,本题中的同步对象是当前的Counter实例。
运行结果如下图所示。
[*]

单项选择题
填空题