Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make threads in Java run concurrently
    primarykey
    data
    text
    <p>I'm trying out this code and I'm a bit confused/surprised at the output I'm getting. I'm still new to Java but I'm aware that threads should normally run concurrently. It seems my "printB" thread here waits for the "printA" thread before it starts executing. I've run the program several times (hoping to get a mixture of both threads' outcome i.e. something like: a, a, b, a, b, a...) but still I get the same output (i.e. "A" getting printed first, before "B"). Why is this happening and how can I alter the code to start behaving normally? </p> <p>Any inputs/suggestions would be much appreciated. Thanks.</p> <p>Also, I'm trying out the same code using the extends Thread method and it doesn't work. </p> <pre><code>class PrintChars implements Runnable{ private char charToPrint; private int times; public PrintChars(char c, int t){ charToPrint = c; times = t; } public void run(){ for (int i=0; i&lt;times; i++) System.out.println(charToPrint); } public static void main(String[] args){ PrintChars charA = new PrintChars('a', 7); PrintChars charB = new PrintChars('b', 5); Thread printA = new Thread(charA); Thread printB = new Thread(charB); printA.start(); printB.start(); } } </code></pre> <p>Extends Thread method below:</p> <pre><code>class PrintChars extends Thread { private Char charToPrint; private int times; public PrintChars(char c, int t){ charToPrint = c; times = t; } public void run (){ for(int i =0; i&lt;times; i++) System.out.println(charToPrint); } PrintChars printA = new PrintChars('a', 7); PrintChars printB = new PrintChars('a', 5); printA.start(); printB.start(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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