日期:2014-05-20  浏览次数:20770 次

总是得不到想要的结果
package xianchengdeyongfa;

public class EraserThread extends Thread {
private boolean active;
private String mask;


public EraserThread(){
this('*');
}


public EraserThread(char maskChar) {
// TODO Auto-generated constructor stub
active = true;
mask = "\010" + maskChar;
}

public void setActive(boolean active){
this.active=active;
}

public boolean isActive(){
return active;
}

public void run(){
while(isActive()){
System.out.print(mask);
try {
Thread.currentThread().sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


}


package xianchengdeyongfa;

import java.util.Scanner;

public class EraserThreadDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("输入名称...");
String name = scan.next();

System.out.println("输入密码...");
EraserThread eraserThread = new EraserThread();
eraserThread.start();
String password = scan.next();
eraserThread.setActive(false);


if("dujianfeng".equals(name)&&"123456".equals(password)){
System.out.println("欢迎杜先生。。。");
}else {
System.out.println("密码或名称输入有误。。。");
}
}

}

}




我想要结果是 输入名称dujianfeng
  输入密码######  
  控制台输出 欢迎杜先生。。。


------解决方案--------------------
稍微有点麻烦:
Console console = System.console();
String pwd = new String( console.readPassword( "Enter Password:", new Object[0] ))

在Eclipse中无法调试,因为获取不到console(控制台)。
------解决方案--------------------
在线程定义的时候有两个问题:
1、active最好用 volatile修饰,写成private volatile boolean active;
2、sleep方法应该Thread.sleep(1000);sleep是静态方法,而Thread.currentThread的结果是一个对象。

程序问题:
只要线程启动,就会一直输出星号