繁体   English   中英

为什么当我按Enter键时程序不会停止

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM