扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
上述的简单解决方案有一个主要缺陷:不应该使用字符串来存储诸如口令这类敏感信息!在本文的余下部分中,将会给出一个经过改进的解决方案。
然而,首先,MaskingThread 类能够从几处改进中获益:
为了确保跨线程的可见性,尤其是在多 CPU 的机器上,stop 字段应该被标记为 volatile.volatile 关键字指定同步线程使用该字段,这样编译器就不会对它进行任何优化;换句话说,应该从内存读取变量的值,而不应该在堆栈中保存任何拷贝。
为了确保屏蔽能够在系统高负荷运转时也能够出现,在调用持续期间,调用线程的优先权被设定为最大。返回时再恢复其原始的优先权。
代码示例 4 显示了修订后的 MaskingThread 类,修改的地方均以粗体形式突出显示。
import java.io.*;
/**
* This class attempts to erase characters echoed to the console.
*/
class MaskingThread extends Thread {
private volatile boolean stop;
private char echochar = '*';
/**
*@param prompt The prompt displayed to the user
*/
public MaskingThread(String prompt) {
System.out.print(prompt);
}
/**
* Begin masking until asked to stop.
*/
public void run() {
int priority = Thread.currentThread().getPriority();
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try {
stop = true;
while(stop) {
System.out.print("\010" + echochar);
try {
// attempt masking at this rate
Thread.currentThread().sleep(1);
}catch (InterruptedException iex) {
Thread.currentThread().interrupt();
return;
}
}
} finally { // restore the original priority
Thread.currentThread().setPriority(priority);
}
}
/**
* Instruct the thread to stop masking.
*/
public void stopMasking() {
this.stop = false;
}
}
婵″倹鐏夐幃銊╂姜鐢瓕鎻╅崚鍥╂畱閹厖绨$憴顤廡妫板棗鐓欓張鈧弬棰侀獓閸濅椒绗岄幎鈧張顖欎繆閹垽绱濋柇锝勭疄鐠併垽妲勯懛鎶姐€婄純鎴炲Η閺堫垶鍋栨禒璺虹殺閺勵垱鍋嶉惃鍕付娴f娊鈧柨绶炴稊瀣╃閵嗭拷