开发者

Multithreading problem using System.out.print vs println

I have the following thread which simply prints a dot every 200ms:

public class Progress {

    private static boolean threadCanRun = true;
    private static Thread progressThread = new Thread(new Runnable() 
    {
        public void run() {
            while (threadCanRun) {
                System.out.print('.');
                System.out.flush();
                try {
                    progressThread.sleep(200);
                } catch (InterruptedException ex) {}
            }
        }
    });

    public static void stop()
    {
        threadCanRun = false;
        progressThread.interrupt();
    }

    public static void start()
    {
        if (!progressThread.isAlive())
        {
            progressThread.start();
        } else
        {
            threadCanRun = true;
        }
    }

开发者_Python百科}

I start the thread with this code (for now):

 System.out.println("Working.");
 Progress.start();


 try {
        Thread.sleep(10000); //To be replaced with code that does work.
 } catch (InterruptedException ex) {}

 Progress.stop();

What's really strange is this:

If I use System.out.println('.'); , the code works exactly as expected. (Apart from the fact that I don't want a new line each time).

With System.out.print('.');, the code waits for ten seconds, and then shows the output.

System.out.println:

     Print dot, wait 200ms, print dot, wait 200ms etc...

System.out.print:

     Wait 5000ms, Print all dots

What is happening, and what can I do to go around this behaviour?

EDIT:

I have also tried this:

private static synchronized void printDot()
{
    System.err.print('.');
}

and printDot() instead of System.out.print('.'); It still doesn't work.

EDIT2:

Interesting. This code works as expected:

        System.out.print('.');
        System.out.flush();  //Makes no difference with or without
        System.out.println();

This doesn't:

        System.err.print('.');
        System.err.flush();
        System.out.print('.');
        System.out.flush();

Solution: The issue was netbeans related. It worked fine when I run it as a jar file from java -jar.

This is one of the most frustrating errors I have seen in my life. When I try to run this code with breakpoints in debug mode, everything works correctly.


The stdout is line buffered. Use stderr, or flush the PrintStream after each print.


(This is weird code -- there are much cleaner ways to write and manage threads. But, that's not the issue.)

Your IDE must be buffering by line. Try running it directly on the command line. (And hope that the shell isn't buffering either, but shouldn't.)


The println method automatically flushes the output buffer, the print method not. If you want to see the output immediately, a call to System.out.flush might help.


I think this is because the println() method is synchronized


(This is not an answer; the asker, David, requested that I follow up on a secondary point about rewriting the threading. I am only able to post code this way.)

public class Progress {

  private ProgressRunnable progressRunnable = new ProgressRunnable();

  public void start() {
    new Thread(progressRunnable).start();
  }

  public void stop() {
    progressRunnable.stop();
  }

  private class ProgressRunnable implements Runnable {

    private final AtomicBoolean running = new AtomicBoolean(true);
    @Override
    public void run() {
      while (running.get()) {
        System.out.print('.');
        System.out.flush();
        try {
          Thread.sleep(200);
        } catch (InterruptedException e) {
        }
      }
    }

    private void stop() {
      running.set(false);
    }

  }

  public static void main(String[] args) {
    Progress progress = new Progress();
    progress.start();
    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
    }
    progress.stop();
  }

}


I tested your code, with System.out.print() and System.out.flush(). The code works for me, except for the code:

while (!threadCanRun)
            {
                 Thread.yield();
            }

in Progress class. Doing that, the thread is pausing allowing other thread to execute, as you can see in the thread api page. Removing this part, the code works.

But I don't understand why do you need the yield method. If you call Progress.stop(), this will cause to invoke the yield method. After the thread will stop with interrupt, (after waiting a huge amount of time on my pc). If you want to allow other threads executing and the current thread pausing, consider the join() method.

If you want to stop the current thread, maybe you can consider to remove the while(!threadCanRun) loop, or place Thread.currentThread().join() before Thread.interrupt() in the stop() method to wait for the completion of other threads, or simply call the p.stop() method .

Take a look to these posts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜