English 中文(简体)
Java的多读
原标题:Multithreading in Java

Hey all
I have a problem with multithreading in java. This is my scenario. I have a class,which name is LocalTime. This class should catch the current time of system, and via a method,which name is getCurrentTime, return this value to a Form. This is the code of this class

public class LocalTime implements Runnable {

 private String currentTime=null;
 Thread t;
 private long time;
 private long h;
 private long m;
 private long s;
 public LocalTime() {
    t=new Thread(this,"current Time");
    t.start();

 }

 public synchronized void run() {

    try {
        for(;;){
        Thread.sleep(1000);
                    time = System.currentTimeMillis()/1000;
                    h = (time / 3600) % 24;
                    m = (time / 60) % 60;
                    s = time % 60;
                    this.currentTime=h+":"+m+":"+s;
        }
     } catch (InterruptedException ex) {
        Logger.getLogger(LocalTime.class.getName()).log(Level.SEVERE, null, ex);
     }

 }
 public String getCurrentTime(){
     return  this.currentTime;
 }

}

并且是主要形式的法典:

public MainForm1() {
    initComponents();
    LocalTime l=new LocalTime();
    this.jLabel1.setText(l.getCurrentTime());//show the current time
    //The rest of code
}


now my major problem is the jLabel1 text which shows current system time does not update each 1 second. If I insert for(;;) before the line of jLabel1.setText(l.getCurrentTime()) the rest of code won t be reacheable. what should I to correct this error? please suggest me solution with these assumptions. I know that I can run a thread in MainForm1, too but I want some solution to this problem.

问题回答

问题是,你刚刚读过一次。 你们要么开始找人查询<代码> 当地时间,要么在<代码>地方时间上添加一个听众,了解时间变化并触发标签更新。

作为附带说明:您不妨结合<条码>新日期(<><>>>>>(<>>>>>)使用<条码>。

除非你不列入重要的法典,否则标签不会不止一次更新。

见您的习惯正在每秒钟一次,更新其自己的代码<>this. Currenttime。

但是,您的标签(至少是你所显示的代码的细微数额),只有经过一次更新(通过<代码>,即:jLabel1.setText(l.getCurrenttime())。 时间为

Just because the local time thread runs, that doesn t mean it will magically go out and update the label. Why would it magically do it if you don t code that yourself? Think about it.

你们需要做的是,在其操作方法中更新标识本身。 此外,这应在Swaod规则(以及如果出现问题)的范围内进行。 各位如何证明,这样,你们就有了干净的法典,这个专题又是另一个read。

// java pseudocode

public void run() {

    Runnable labelUpdater = new Runnable()
    {
      public void run()
      {
        someForm.jLabel1.setText(yourUpdatedTimeFormattedAsStringOrWhatever);
      }
    }
    try {
        for(;;){
           Thread.sleep(1000);
           // will cause label update to occur in the awt event queue
           SwingUtils.invokeLater(labelUpdater); 
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(LocalTime.class.getName()).log(Level.SEVERE, null, ex);
    }

}

一些说明:

  1. You don t need the synchronized keyword in this specific instance of your run() method.
  2. Use java.util.Calendar and java.util.Format to get string representations of the current time. What you are doing there with all that string concatenation and dividing the output of System.currentTimeMillis() is just bad. Have you looked at the Java API to see what s already there for you????????

改为:

Concurrency in Swing http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html#event_dispatching

Concurrency (the Java Tutorial) http://download.oracle.com/javase/tutorial/essential/concurrency/

Please, please use a Timer for that kind of task... Why go to all that extra complexity? Try something like this:

  int delay = 1000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
     final LocalTime locTime = new LocalTime();
     public void actionPerformed(ActionEvent evt) {
         jLabel1.setText(locTime.getCurrentTime());
     }
  };
  new Timer(delay, taskPerformer).start();

创建timerTask,并在时间运行方法中打电话setText。 然后slate 这项任务将每两年执行一次。

只是一个错误之处是每秒更新标签。 正在通过使用系统日期计算时间的路面是罚款。 可以做的是,每二次会后会增加一次活动,并改变活动听众的字面价值。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...