Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing data to console at the same time printinf information in java

I want to know how to control the console print format. My problem is that I have 2 threads, one of them constantly prints information to the console, and the other constantly asks the user to write information, but while writing if the other thread prints something, it cuts the phrase the user is writing and splits it. How do you control it?

My code of thread 1:

//Definition of variables

while (exit == false) {
    scanner = new Scanner(System.in);
    message = scanner.nextLine();
}

//Code to use user input

My code of thread 2:

//Definition of variables

while (receive.getExecutingState()) {  
    srvMsg = receive.Receive();
    System.out.println(srvMsg);
}

Console output:

No more data to show.
No more data to show.
hNo more data to show.
eNo more data to show.
llo

I want it to keep printing messages while the user write data but don't split what it's writing.

Thanks in advance!

Edit: As said by @Thomas what I want in a clearer way, is to keep the text the user is writing at the bottom of the console, and the rest being updated.

like image 479
Aníbal Muñoz Avatar asked Feb 05 '16 12:02

Aníbal Muñoz


People also ask

How do you print to console in Java?

println(): println() method in Java is also used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the start of the next line at the console.

What is the difference between print () and println () when printing out to the console?

The prints method simply print text on the console and does not add any new line. While println adds new line after print text on console.

What does printing \\ do in Java?

The print() method is used to print text on the console. It is an overloaded method of the PrintStream class. It accepts a string as a parameter. After printing the statement, the cursor remains on the same line.

Which statement is used to print the message in the same line in Java?

println() is used to print an argument that is passed to it. The statement can be broken into 3 parts which can be understood separately as: System: It is a final class defined in the java. lang package.


1 Answers

One way would be to read the character from the users one by one:

  • let the writing thread write
  • if user enters one character (or more) pause the writing thread until the user presses enter
  • when the user presses enter, resume the writing thread

The pause/resume mechanism could be done in several ways, for example by using a Sempahore with one permit that is taken by the reading thread or the writing thread in turn.

like image 172
assylias Avatar answered Oct 04 '22 21:10

assylias