Java 如何使变量在背景中每隔一秒递增
我的问题是我需要在代码中包含一个时钟。问题是,我不知道如何在不完全暂停整个代码的情况下每秒递增一次。有人能告诉我一种更好的方法吗?或者有人能告诉我一个变量在java中每秒可以增加多少次,这样我就可以用%来计算时钟需要增加多少次 代码:Java 如何使变量在背景中每隔一秒递增,java,increment,clock,Java,Increment,Clock,我的问题是我需要在代码中包含一个时钟。问题是,我不知道如何在不完全暂停整个代码的情况下每秒递增一次。有人能告诉我一种更好的方法吗?或者有人能告诉我一个变量在java中每秒可以增加多少次,这样我就可以用%来计算时钟需要增加多少次 代码: 我认为这是一种家庭作业,因为否则你当然可以使用内部时钟 您需要将更新逻辑放入并行运行的新线程中。编写一个runnable()并在其中包含一个循环(可能是while(true)),用于执行更新。我在这个地址发现了以下Java计时器示例: 该示例假设您正在使用Java
我认为这是一种家庭作业,因为否则你当然可以使用内部时钟
您需要将更新逻辑放入并行运行的新线程中。编写一个runnable()并在其中包含一个循环(可能是
while(true)
),用于执行更新。我在这个地址发现了以下Java计时器示例:
该示例假设您正在使用Java.Swing库,并且您需要应用程序的UI,而不是使用控制台
ClockLabel.java
// An extension of the JLabel class that listens to events from a Timer object to
// update itself with the current date & time.
import java.util.Date;
import java.awt.event.*;
import javax.swing.*;
public class ClockLabel extends JLabel implements ActionListener {
public ClockLabel( ) {
super("" + new Date( ));
Timer t = new Timer(1000, this);
t.start( );
}
public void actionPerformed(ActionEvent ae) {
setText((new Date( )).toString( ));
}
}
import javax.swing.*;
import java.awt.*;
public class ClockTest extends JFrame {
public ClockTest( ) {
super("Timer Demo");
setSize(300, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
ClockLabel clock = new ClockLabel( );
getContentPane( ).add(clock, BorderLayout.NORTH);
}
public static void main(String args[]) {
ClockTest ct = new ClockTest( );
ct.setVisible(true);
ClockTest.java
// An extension of the JLabel class that listens to events from a Timer object to
// update itself with the current date & time.
import java.util.Date;
import java.awt.event.*;
import javax.swing.*;
public class ClockLabel extends JLabel implements ActionListener {
public ClockLabel( ) {
super("" + new Date( ));
Timer t = new Timer(1000, this);
t.start( );
}
public void actionPerformed(ActionEvent ae) {
setText((new Date( )).toString( ));
}
}
import javax.swing.*;
import java.awt.*;
public class ClockTest extends JFrame {
public ClockTest( ) {
super("Timer Demo");
setSize(300, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
ClockLabel clock = new ClockLabel( );
getContentPane( ).add(clock, BorderLayout.NORTH);
}
public static void main(String args[]) {
ClockTest ct = new ClockTest( );
ct.setVisible(true);
这将每秒调用一个合适的方法:
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
final Runnable task = () -> myObj.incrementSeconds();
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(task, 1, 1, SECONDS);
private final ScheduledExecutorService调度器=
Executors.newScheduledThreadPool(1);
最终可运行任务=()->myObj.incrementSeconds();
最终计划的未来蜂鸣器手柄=
scheduleAtFixedRate(任务,1,1,秒);
请注意,多线程访问变量存在问题,因此在依赖多线程之间共享的变量之前,您应该确保了解原子性、volatile关键字等主题。有很多关于Java并发性的书
然而,您似乎正在编写一个时钟类。已经有了非常灵活和可靠的
java.time.Clock
。这就是Javax.Swing.Timer类的好处,或者ScheduledExecutorService
而ScheduledExecutorService
可以做到这一点,您是否考虑过只使用java.time.Clock
?如果您已经在使用Swing,那么答案是可以接受的。不要将Swing仅仅用作计时器。