Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A couple of things before the explanation:</p> <p>It's unnecessary to extend <code>Thread</code>, and it is easier to just implement <code>Runnable</code>, which provides the <code>run</code> method that you are implementing. At this point, you can give the <code>Runnable</code> to a <code>Thread</code> or, more usefully, an <code>Executor</code> (very useful for multithreading in Java).</p> <p>Also, wrapping <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/System.html" rel="nofollow"><code>System.out</code></a> in a <code>PrintStream</code> is redundant, as <code>System.out</code> is already a <code>PrintStream</code> itself.</p> <p>Finally, your code is not sharing anything, which is why they do not interfere with each other. All each one does is print out their name and a unique letter so you can find it. <code>System.out</code> is thread safe in the Sun implementation (as noted by Andre, that's technically not required by JVM implementations), so you will not be able to break output up, but that does not stop you from potentially interweaving output.</p> <p>For example, if you run this enough, then you could easily see:</p> <pre><code>thread 1 a thread 2 a thread 1 b thread 2 b </code></pre> <p>However, I suspect that you are seeing:</p> <pre><code>thread 1 a . . . thread 1 k thread 2 a . . . thread 2 k </code></pre> <p>This is not because something is broken, rather it's because the thread executes so quick that it just happens that way. Since you are learning, it would be good to add in some <code>Thread.sleep</code> calls between output with random delays so that you can hopefully observe the interweaving.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload