【发布时间】:2019-04-07 02:13:01
【问题描述】:
我正在编写一个 java 应用程序,它将重复地散列一系列输入值,直到满足条件。我通过在 while 循环中嵌套一系列 if/else 语句来实现这一点。我希望能够在应用程序主动散列时每 3 秒将散列率打印到终端,并且在满足条件之前不要重复。我曾尝试使用 ExecutorService 并安排 TimerTask ,但两者都没有按照我希望的方式工作,因为在满足应该停止它们的条件后它们都继续执行。我知道我错过了一些东西,但我不知道是什么):
我已经包含了一个小sn-p,请随时询问您可能认为相关的任何信息。
任何帮助将不胜感激!
我尝试使用这样的 TimerTask:
while(iterator) {
if (difficulty == 1) {
if (!hash.startsWith("0")) {
long updatedTime = System.nanoTime();
Nonce++;
long deltaN = updatedTime - startTime;
long deltaS = (deltaN / 1000000000);
long hashRate = (Nonce / deltaS);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Current hash rate: " + hashRate + " " + "hash/s");
}
}, 0, 3000);
} else {
System.out.println("Valid hash found! " + hash);
iterator = false;
}
}
}
编辑:完成后的内容本质上是一个俗气的“区块链”,我将用作说明目的作为教学工具,考虑到这一点,我在下面包含了“矿工”方法的其余部分:
public void miner(long index, long currentTimeMillis, long data, long Nonce, String previousBlockHash, int difficulty) throws InterruptedException {
this.index = index;
this.currentTimeMillis = currentTimeMillis;
this.pszTimeStamp = pszTimeStamp;
this.Nonce = Nonce;
this.previousBlockHash = previousBlockHash;
this.difficulty = difficulty;
this.data = data;
boolean iterator = true;
String blockHeader = (index + currentTimeMillis + data + Nonce + previousBlockHash + difficulty);
String hash = SHA256.generateHash(blockHeader);
long startTime = System.nanoTime();
TimeUnit.SECONDS.sleep(2);
while (iterator) {
blockHeader = (index + currentTimeMillis + data + Nonce + previousBlockHash + difficulty);
hash = SHA256.generateHash(blockHeader);
if (difficulty == 1) {
if (!hash.startsWith("0")) {
long updatedTime = System.nanoTime();
Nonce++;
long deltaN = updatedTime - startTime;
long deltaS = (deltaN / 1000000000);
long hashRate = (Nonce / deltaS);
System.out.println("Current hash rate: " + hashRate
} else {
System.out.println("\n");
System.out.println("Hash found! \n");
System.out.println("Mined block hash: \n" + hash);
}
} else if (difficulty == 2) {
...........
“miner”方法采用的所有参数都由包含主函数的启动类传递给它。我的目标是能够在每隔几秒搜索一次“有效”哈希时打印哈希率,而不是每秒打印数千次。
【问题讨论】:
标签: java if-statement while-loop