原理很简单,就是另外启动一个线程,不停的写提示输入密码,而主线程负责读密码.
public class CTest implements Runnable
{
Thread thread = null;
public boolean flag = false;
public static void main(String s[])
{
try
{
StringBuffer password = new StringBuffer();
CTest c = new CTest();
c.test();
while(true)
{
char cc = (char)System.in.read();
c.flag = true;
if(cc != ''\r'' && cc != ''\n'')
{
password.append(cc);
}
if(cc == ''\n'')
{
break;
}
}
System.out.println("Your password is:" + password.toString());
}
catch(Exception e )
{
System.out.println(e);
}
}
public void run()
{
while(!flag)
{
try
{
System.out.print("\r" + "Please enter your password:" + " \r" );
thread.sleep(10);
}
catch(Exception e)
{}
}
}
public void test() throws Exception
{
if(thread==null)
{
thread=new Thread(this);
thread.start();
}
}
}
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/










