[英]Why won't my program stop when I press enter
試圖創建一個可以創建隨機密碼的小應用程序,而我目前正處於設法讓用戶停止該應用程序的階段。 但是,循環繼續進行,不會到達我的掃描儀,但是由於某種原因,如果我取消使用掃描儀和同步代碼塊,則此代碼將起作用。
無論如何,此代碼有什么問題?:
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;
}
}
您的running
是易變的,訪問易失成員的隱含同步在包含它的對象上進行。 檢查此: http : //www.javamex.com/tutorials/synchronization_volatile.shtml
對(volatile)變量的訪問就好像它被封裝在一個同步塊中,並在其自身上同步
因此,通過調用passwordGenerator
的線程來獲取pG
的鎖定。 它從不釋放它。 因此,您的main
在調用shutDown
時試圖訪問running
時會陷入困境
該問題與您的掃描儀無關
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.