尝试创建一个小应用程序来创建随机密码以获得它的乐趣,而我目前正处于试图让我的用户停止应用程序的阶段。然而,循环继续前进并且无法进入我的扫描仪,但由于某种原因,如果我取消使用扫描仪和同步代码块,这段代码将起作用。
无论如何,这段代码出了什么问题?:
public class Application {
public static void main(String[] args) {
Scanner stopScanner = new Scanner(System.in);
final PasswordGenerator pG = new PasswordGenerator();
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
try {
pG.passwordGenerator();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.run();
System.out.println("Press enter to stop!");
stopScanner.nextLine();
pG.shutDown();
}
}
class PasswordGenerator{
private volatile static boolean running = true;
protected Scanner scan = new Scanner(System.in);
public void passwordGenerator() throws InterruptedException{
synchronized(this){
System.out.println("Select charecter set:");
System.out.println(" 1: ABCDEF");
System.out.println(" 2: GHIJKL");
System.out.println(" 3: MNOPQR");
System.out.println(" 4: TUVWXYZ");
String charecters = scan.nextLine();
System.out.println("Select a password length");
int number = scan.nextInt();
scan.nextLine();
if(number <= 6){
System.out.println("Number cannot be smaller or equal to six!");
} else {
switch(charecters){
case "1":
while(running == true){
System.out.println("placeholder");
Thread.sleep(1000);
}
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
System.out.println("No valid set chosen!");
break;
}
}
}
}
public void shutDown(){
running = false;
}
}
答案 0 :(得分:-2)
您的running
是易失性的,访问volatile成员会在包含它的对象上隐式同步。检查一下:http://www.javamex.com/tutorials/synchronization_volatile.shtml
对(volatile)变量的访问就好像它被包含在一个同步的块中,自身同步
因此,调用pG
的线程获取passwordGenerator
的锁定。它永远不会释放它。因此,main
在调用running
shutDown
无法访问data want;
infile 'myfile.csv' dsd firstobs=2 truncover;
length var1 $20 var2 8 ... varlast 8 ;
informat var2 yymmdd10.;
format var2 yymmdd10.;
input var1 -- varlast;
run;
问题与您的扫描仪无关