想编写一个世界时钟的小程序,因为需要用上Swing的组件,而且要使用多线程,来获取不同国家的时间,每个时间用一个线程改变组件的值,怎样在一个类中实现,我编了一个但是感觉不符合要求
public void run(){
while(true){
Calendar now=Calendar.getInstance();
now.add(Calendar.HOUR,0);
String sdf=new SimpleDateFormat("HH:mm:ss").format(now.getTime());
l5.setText(sdf);
now.add(Calendar.HOUR,-12);
sdf=new SimpleDateFormat("HH:mm:ss").format(now.getTime());
l6.setText(sdf);
now.add(Calendar.HOUR,-7);
sdf=new SimpleDateFormat("HH:mm:ss").format(now.getTime());
l7.setText(sdf);
now.add(Calendar.HOUR,+2);
sdf=new SimpleDateFormat("HH:mm:ss").format(now.getTime());
    l8.setText(sdf);
}
}
public static void main(String[] args) {
WorldTime w=new WorldTime();
new Thread(w).start();
w.setVisible(true);
}
这是关于线程的部分,l5到l8时4个时间的标签,我这个好像是单线程,怎样用四个线程来改变标签的值,并且在一个类中呢

解决方案 »

  1.   

    1.把线程类和界面类分开,比如界面类叫YourFrame,线程类叫YourThread
    2.now.add(Calendar.HOUR,-12); 把-12当作一个参数传给线程。
    3.把YourFrame的时间控件也当作一个参数传给线程。
       线程的构造参数这样 public YourThread(JText text, int addHour){}
    4.run方法像这样
    public void run(){
    while(true){
    Calendar now=Calendar.getInstance();
    now.add(Calendar.HOUR,addHour);
    String sdf=new SimpleDateFormat("HH:mm:ss").format(now.getTime());
    text..setText(sdf);Thread.sleep(100); //停顿一下5.启动界面的Main函数改成这样
    public static void main(String[] args) {
    YourFrame frame = new YourFrame();
    YourThread y1 = new YourThread(frame.l5,0);
    YourThread y2 = new YourThread(frame.l6,-12);
    YourThread y3 = new YourThread(frame.l7,-7);
    YourThread y4 = new YourThread(frame.l8,2);
    y1.start();
    y2.start();
    y3.start();
    y4.start();
    frame.setVisible(true);
    }
    6.以上为思路,照着改一改
      

  2.   

    Java 多线程 之 银行ATM实例http://www.verejava.com/?id=16992914422268