Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - StringBuilder not accessible after while loop in thread

class myThread extends Thread {

myThread(Socket socket) {
    Scanner sc = new Scanner(socket);
}

public void run() {
    StringBuilder sb = new StringBuilder();
    try {
        while(sc.hasNext()) {
            sb.append(sc.next());
            sb.append(" ");
        }
        System.out.println(sb.toString());      

    } catch (Exception e) {
        System.out.println(e);      
    }
}

This code doesn't output anything. However, If I move the System.out.println(sb.toString()); into the while loop, it does. I have no idea why this is, but I need the code to output first AFTER the while loop is complete.

How would one go about to print the StringBuilder.toString() after the while-loop is complete?

like image 215
V.Vocor Avatar asked Sep 24 '26 13:09

V.Vocor


1 Answers

The socket is probably never being closed, and the scanner is just blocking on hasNext().

Close the socket and it should finish.

like image 108
aglassman Avatar answered Sep 26 '26 05:09

aglassman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!