Java 我正试图写一个程序,将显示时间和日期时,按钮被点击
我正在尝试编写一个程序,当点击它时,它将启动一个新的Java 我正试图写一个程序,将显示时间和日期时,按钮被点击,java,multithreading,Java,Multithreading,我正在尝试编写一个程序,当点击它时,它将启动一个新的线程,然后显示日期和时间,但它并没有像我预期的那样工作。任何帮助都将不胜感激 import java.applet.Applet; import java.awt.Button; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.
线程
,然后显示日期和时间,但它并没有像我预期的那样工作。任何帮助都将不胜感激
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
/**
* @author Hobbit
*
*/
public class Myapp extends Applet implements Runnable,ActionListener {
Button b; // I'm creating a button named b
Thread t;
/* (non-Javadoc)
* @see java.applet.Applet#init()
*/
public void init() {
b = new Button(":)");
add(b);
b.addActionListener(this);
}
/* (non-Javadoc)
* @see java.awt.Container#paint(java.awt.Graphics)
*/
public void paint(Graphics g) {
Date d = new Date();
g.drawString(d + "", 50, 50);
setBackground(Color.green);
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
while(true) {
repaint();
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent f) {
// If the button is clicked then it should trigger the thread
if (f.getSource() == b);
{
Thread t = new Thread();
t.start();
}
}
}
代码有多个问题,但最重要的是,
线程
什么也不做。如果您想让它做一些事情,您需要向它传递一个Runnable
,如下所示:
Runnable myAwesomeRunnable = new Runnable() {
public void run() {
System.out.println(new Date());
}
};
Thread t = new Thread(myAwesomeRunnable);
t.start();
实际上,我建议使用这种方法,而不是实现MyApp
类中的所有接口,因为我相信这样更干净,更容易理解发生了什么,但是,在您的示例中,您还可以使用:
Thread t = new Thread(this);
t.start();
由于此
是可运行的
的一个实例
另一件事是,你没有真正检查哪个按钮被按下。这段代码:
// If the button is clicked then it should trigger the thread
if (f.getSource() == b);
{
Thread t = new Thread();
t.start();
}
由于if
语句后面的分号,导致线程始终启动。如果希望If
决定是否启动线程,则代码应如下所示:
// If the button is clicked then it should trigger the thread
if (f.getSource() == b) {
Thread t = new Thread(myAweSomeRunnable);
t.start();
}
线程对象是空的。也许你想要的是新线程(this)(因为“this”是可运行的)如果它不工作,它在做什么?那里也有一个空的If语句。我在If语句中创建了一个新线程。如果它工作,请回答你自己的问题。