Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        3年前关闭。
                                                                                            
                
        
我有以下代码,但是我希望它每秒运行一次,因此,如果questNumber更改,那么currentQuestStats也将更改。
代码:http://pastebin.com/jTAwztPX

最佳答案

使用JAVA 5中添加的ScheduledExecutorService,必须导入以下类。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;




您可以像下面这样使用它:

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        // TODO add your code here:
    }
}, 0, 1, TimeUnit.SECONDS);




回答


checkQuestNumber()类中创建一个称为QuestsManagement的方法。
还为QuestsManagement创建一个构造函数
使用此值(currentQuestStats)初始化§e§lCurrent quest: Kill 1 zombie
currentQuestStatsquestNumber设为私有并封装它们。


更改后,这是您的QuestsManagement

public class QuestsManagement {

    private String currentQuestStats = "§e§lCurrent quest: Kill 1 zombie";
    private int questNumber = 1;

    public String getCurrentQuestStats() {
        return currentQuestStats;
    }

    public int getQuestNumber() {
        return questNumber;
    }

    QuestsManagement() {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
               checkQuestNumber();
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    void checkQuestNumber() {

        if (questNumber == 1) {
            currentQuestStats = "§e§lCurrent quest: Kill 1 zombie";
            // change manual!
            questNumber = 2;
        } else if (questNumber == 2) {
            currentQuestStats = "§e§lCurrent quest: Walk 100 blocks";
            // change manual!
            questNumber = 1;
        }
    }
}


要测试代码!

在您的自定义命令文件中

创建QuestsManagement的实例并使用getCurrentQuestStats()方法

QuestsManagement m = new QuestsManagement();
player.addChatMessage("Test" + QuestsManagement.getCurrentQuestStats());

10-06 07:23