简体   繁体   English

线程不会在Java上启动

[英]Thread wont start on Java

The following code should produce a regular frame with time in it, when the time hit 90 minutes it should display a message. 以下代码应生成一个带有时间的常规帧,当时间达到90分钟时,它将显示一条消息。 somehow the Thread wont start and the message Thread is working properly is never displayed. 线程将不会以某种方式启动,并且永远不会显示消息Thread is working properly i have already read the following Oracle article but couldn't find any solution. 我已经阅读了以下 Oracle文章,但找不到任何解决方案。

public class Core extends JFrame implements Runnable{

private int second;
private int minute;
private JLabel presentor;
private Thread threadObject = new Thread();

public Core(){
    second = 1;
    minute = 0;
    presentor = new JLabel();
    writeLabel();
    add(presentor , BorderLayout.CENTER);
    threadObject.start();
}

public void run(){
    JOptionPane.showMessageDialog(null, "Thread is working properly");
    try{Thread.sleep(60000);}
    catch(InterruptedException e){e.printStackTrace();}
    updateTime();
    writeLabel();
    if(minute > 89){
        JOptionPane.showMessageDialog(null, "90 minutes have passed away , take a break!");
        this.getParent().setFocusable(true);
    }
}

public void writeLabel(){
    presentor.setText(minute + ":" + second);
}

public void updateTime(){
    second++;
    if(second < 60)
        return;
    second = 0;
    minute++;

}

} }

there is also a class with the Main method which have the basic frame setting, nothing important there. 还有一个带有Main方法的类,它具有基本的框架设置,在那里没有什么重要的。

您没有为Thread指定Runnable参数(由于核心类实现了Runnable ,因此我认为应该是this参数):

private Thread threadObject = new Thread(this);

TNT's answer is correct, but it's not complete. TNT的答案是正确的,但还不完整。 Your program has more than one problem. 您的程序有多个问题。 The next problem you will face is that there's no loop in your run() method. 您将面临的下一个问题是run()方法中没有循环。 It will call updateTime() and writeLabel() exactly once, and then the thread will terminate. 它将只调用一次updateTime()和writeLabel(),然后线程将终止。

The next problem after that, is in your updateTime() method. 之后的下一个问题是您的updateTime()方法中。 It appears as if it's meant to count seconds, but your run() method looks like, if it had a loop, it would only call updateTime() once every minute. 看起来好像是要数秒,但是您的run()方法看起来像是如果有一个循环,则每分钟只会调用一次updateTime()。 That means it will take 90 HOURS, not 90 minutes before your program pops up the dialogue. 这意味着您需要90小时(而不是90分钟),程序才会弹出对话框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM