温馨提示×

java定时器如何实现文字内容交换

小亿
82
2024-06-12 09:18:33
栏目: 编程语言

在Java中实现文字内容交换可以使用定时器和定时任务来实现。以下是一个简单的示例代码:

import java.util.Timer;
import java.util.TimerTask;

public class TextSwitcher {

    private String text1 = "Hello";
    private String text2 = "World";
    private String currentText = text1;

    public void startTextSwitching() {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (currentText.equals(text1)) {
                    currentText = text2;
                } else {
                    currentText = text1;
                }
                System.out.println(currentText);
            }
        };
        timer.scheduleAtFixedRate(task, 0, 1000); // 切换文字每隔1秒
    }

    public static void main(String[] args) {
        TextSwitcher textSwitcher = new TextSwitcher();
        textSwitcher.startTextSwitching();
    }
}

在这个示例中,我们创建了一个TextSwitcher类,其中包含两个文字内容text1text2,并定义了一个定时器任务来切换当前显示的文字内容。定时器每隔1秒调用一次任务,根据当前显示的文字内容来切换到另一个文字内容,并输出到控制台上。你可以根据自己的需求对定时器的时间间隔进行调整。

0