此applet显示时间和每30秒更改一次的字符串到另一个字符串,有5个这样的字符串。
问题是在执行期间字符串不会像预期的那样改变。他们通常会跳过订单。
我想知道这种方法有什么问题?
package applet;
import java.applet.Applet;
import java.awt.Graphics;
import java.text.SimpleDateFormat;
import java.util.*;
public class Project1 extends Applet implements Runnable {
String[] str = new String[4];
int index=0;
private static final long serialVersionUID = 1L;
Thread t,t1;
public void start(){
setSize(getMaximumSize());
t = new Thread(this);
t.start();
str[0] = "Hope for the best, but prepare for the worst.";
str[1] = "You can't judge a book by its cover.";
str[2] = "Do unto others as you would have them do unto you.";
str[3] = "Practice makes perfect.";
}
public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
int sec = cal.get(Calendar.SECOND);
if(sec ==30 ||sec == 60){
++index;
}
if(index > 4) index =0;
g.drawString(str[index], 400, 300);
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm.ss aa");
String formattedDate = dateFormat.format(new Date()).toString();
g.drawString(formattedDate,800,30);
g.drawString("Counter: " + (index+1), 600, 400);
}
}
答案 0 :(得分:0)
java Thread :: sleep(int millisecond)在你传递给它的确切时间内没有睡觉,而是睡眠至少毫秒#34; 并且重新打印不会被要求立即使您的观点无效。它可以随时调用paint。 而paint方法可以每秒多次调用。