Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>run</code> method that is implemented by a thread needs to be in a separate class. You can certainly put one of them in your <code>ThreadExperiment</code> class, but it can't be both. In this case, you can separate the two threads into inner classes:</p> <pre><code>class ThreadExperiment { static int num = 1; static int num2 = 10; class Thread1 implements Runnable { @Override public void run(){ do { num++; try { Thread.sleep(400); } catch (InterruptedException e){ } } while (num &gt;= 0); } } class Thread2 implements Runnable { @Override public void run() { do { num2--; try { Thread.sleep(400); } catch (InterruptedException e){ } } while (num &gt;= 1); } } public static void main(String[] args) { Thread t = new Thread(new Thread1()); Thread t2 = new Thread(new Thread2()); t.start(); t2.start(); if (num == num2) { t.interrupt(); t2.interrupt(); } } } </code></pre> <p>Now we're getting somewhere, but you still need to fix some issues with your logic:</p> <ul> <li>Having the <code>int</code>s as static isn't good practice. (But it's okay for this testing scenario.)</li> <li>Your <code>num == num2</code> check will happen only once and there are no guarantees on what the values will be there when that happens. It is very unlikely that the threads will be interrupted.</li> <li>You need to declare the <code>int</code>s <code>volatile</code> since they will be read by different threads.</li> <li>The <code>while</code> condition in <code>Thread1</code> will result in an infinite loop.</li> </ul>
    singulars
    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