在主方法中保持扫描器运行/监听(两个线程)

时间:2014-08-27 18:05:14

标签: java multithreading

问题描述:

修改这些文件以便能够以交互方式要求用户提供要显示的广告消息。用户键入要显示的消息并按ENTER键。接受用户输入的消息。显示用户请求作为广告消息的消息,在显示之间重复暂停1秒。

如果用户再次按下ENTER(在显示上一条消息时),程序应该询问用户是否有新的(已修改的)消息。用户键入新消息并按ENTER键。广告显示现在应该更改为显示新消息显示,重复显示之间暂停1秒。当用户输入n(不区分大小写)时退出程序。

如果我使用下面的代码,第一次输入消息时它正常工作,当我按Enter键时,重复打印消息会被正确中断,并提示我输入新消息。但是,当我单击输入时,由于主方法已完成,因此不会中断重复打印:

import java.util.Scanner;
class Advertisement extends Thread
{
    private boolean done = false;
    String message = "";
    public void run()
    {
        Thread myThread = Thread.currentThread();
        while (!isDone())
        {
            System.out.println("Please enter the advertisement message to be displayed   
                   (enter 'n' to exit):");
            Scanner sc2 = new Scanner(System.in);
            message = sc2.nextLine();
            if (message.equalsIgnoreCase("n"))
            {
                done = true;
                System.out.println("User Stopped the Message Output");
                continue;
            }

            while (!(myThread.isInterrupted()))
            {
                try
                {
                    System.out.print("** " + message + " **");
                    myThread.sleep(1000);
                }
                catch (InterruptedException e)
                {  
                    System.out.println("Exception caught: " + e.getMessage());
                    break;
                }
            }
        }
    }// end of 'run()' ..
    /**
     * @return the done
     */
    public boolean isDone()
    {
        return done;
    }

}

import java.util.Scanner;

public class TestAdvt2
{
    public static void main (String[] args)
    {
        Advertisement advt = new Advertisement();
        advt.start();
        Scanner sc = new Scanner(System.in);
        String str = "start";
        while (!((str.equals(""))))
        {
            str = sc.nextLine();
        }
        advt.interrupt();
    }
}

如果我将main方法更改为包含while循环,则中断将完全停止工作。

import java.util.Scanner;
class TestAdvt
{
    public static void main (String[] args)
    {
        Advertisement advt = new Advertisement();
        advt.start();
        Scanner sc = new Scanner(System.in);
        boolean done = false;
        while (done == false);
        {
            String str = "start";
            while (!((str.equals(""))))
            {
                str = sc.nextLine();
            }
            done = advt.isDone();
            advt.interrupt();
        }
    }
}

有关如何使其工作以便可以更改消息的任何建议将不胜感激。

更新:

我能够使用您的建议来修复我的代码。我需要做一些清理并使用synchronized关键字而不是volatile关键字(这是老师想要的)。

这是固定代码:

import java.util.Scanner;

/**
*
* @author Jeanne Gaskill
*/

public class Advertisement2 extends Thread
{
    private boolean done = false;
    String message = "";

    public void run() 
    {
        Thread myThread = Thread.currentThread();
        while (true) 
        {
            while (!done) 
            {
                System.out.println("\n\nPlease enter the advertisement message to be displayed "
                    + "(type message or enter 'n' to exit):\n");
                Scanner sc2 = new Scanner(System.in);
                message = sc2.nextLine();
                done = true;
                System.out.println("\n");
                if (message.equalsIgnoreCase("n")) 
                    {
                        System.out.println("User Stopped the Message Output");
                        // Terminating
                        System.exit(0);
                        continue;
                    }
                while (!(myThread.isInterrupted())) 
                {
                    try 
                    {
                        System.out.print("** " + message + " **");
                        Thread.sleep(1000);
                    } 
                    catch (InterruptedException e) 
                    {
                        // System.out.println("Exception caught: " + e.getMessage());
                        done = false;
                        break;

                    }
                }
            }
        }
    }// end of 'run()' ..

    /**
    * @return  done variable
    */
    synchronized public boolean isDone() 
    {
        return done;
    }    

    /**
     * @param done  to set done variable
     */
    synchronized public void setDone(boolean done)
    {
        this.done = done;
    }

}

import java.util.Scanner;

public class TestAdvt
{
    public static void main (String[] args)
    {    
        Advertisement advt = new Advertisement();
        advt.start();
        Scanner sc = new Scanner(System.in);
        while (true) 
        {
            while (advt.isDone()) 
            {
                // main thread is listening
                String str = sc.nextLine();

                // check for new line
                if (str.equals("")) 
                {
                    advt.interrupt();
                }
                advt.setDone(false);
            }
        }
    }

}

@Jigar

再次感谢!

1 个答案:

答案 0 :(得分:0)

代码中的几件事

  • 只有在广告话题没有收听时以及刚刚打印时,你才需要继续收听主要内容

  • 您需要将volatile用于标志变量

  • 正确控制旗帜

摘要this is the code you need,格式,清理,在您身边