本人才接触java没多久,如觉得问题太小白请原谅...今天看到一个模拟屏幕用户命令行输入的例子,其中有一点弄不明白,所以特意来请教下大家
其中一个类是来记录用户输入字符的,如下:
import java.io.*;public class InputMasking extends Thread
{
String getPassword(String initial) throws IOException,Exception
{
MaskingThread listeningthread = new MaskingThread(initial);
Thread thread_instance = new Thread(listeningthread);
String password = "";
thread_instance.start();
while (true)
{
this.sleep(100);
char input = (char)System.in.read();
listeningthread.stopMasking(); //问题所在..
if (input == '\r')
{
input = (char)System.in.read();
if (input == '\n')
break;
else
continue;
}
else if(input == '\n')
break;
else
password += input;
}
return password;
}
}另外一个我觉得主要是用来刷屏的,以此来给人感觉是屏蔽掉输入了,如下:
import java.io.*;class MaskingThread extends Thread
{
private boolean stop = false;
private int index;
private String initial; public MaskingThread(String initial)
{
this.initial = initial;
}
public void run()
{
while(!stop)
{
try
{
this.sleep(1);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
if (!stop)
{
System.out.print("\r" + initial + " \r" + initial);
}
System.out.flush();
}
}
public void stopMasking()
{
this.stop = true;
}
}现在的问题就是,在第一个类里面调用了stopMasking()方法,这个时候变量stop就是true了,下次判断while循环的时候为什么还能继续循环呢?
其中一个类是来记录用户输入字符的,如下:
import java.io.*;public class InputMasking extends Thread
{
String getPassword(String initial) throws IOException,Exception
{
MaskingThread listeningthread = new MaskingThread(initial);
Thread thread_instance = new Thread(listeningthread);
String password = "";
thread_instance.start();
while (true)
{
this.sleep(100);
char input = (char)System.in.read();
listeningthread.stopMasking(); //问题所在..
if (input == '\r')
{
input = (char)System.in.read();
if (input == '\n')
break;
else
continue;
}
else if(input == '\n')
break;
else
password += input;
}
return password;
}
}另外一个我觉得主要是用来刷屏的,以此来给人感觉是屏蔽掉输入了,如下:
import java.io.*;class MaskingThread extends Thread
{
private boolean stop = false;
private int index;
private String initial; public MaskingThread(String initial)
{
this.initial = initial;
}
public void run()
{
while(!stop)
{
try
{
this.sleep(1);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
if (!stop)
{
System.out.print("\r" + initial + " \r" + initial);
}
System.out.flush();
}
}
public void stopMasking()
{
this.stop = true;
}
}现在的问题就是,在第一个类里面调用了stopMasking()方法,这个时候变量stop就是true了,下次判断while循环的时候为什么还能继续循环呢?
而while(true){}是一个死循环,死循环的意思就不要解释了吧,只要有东西读,那么listeningthread.stopMasking();就会一遍又一遍的执行.......
listeningthread.stopMasking()这个方法只要执行一次不就改变了 stop 的值了吗?哪么为什么MaskingThread 这个线程不会停止呢?