简体   繁体   中英

Java Thread outputting answer wrong

package task1;

import java.lang.Thread;


public class Counter implements Runnable{
    int num;
    boolean odd;
    boolean even;


    public Counter(int i,boolean odd, boolean even){
        this.num=i;
        this.odd=odd;
        this.even=even;
    }

    @Override
    public void run() {
        if(odd==true&even==false){
            System.out.print("\nOdd numbers\n");
            
            for(int j=this.num; j<=10; j+=2){  
                System.out.print(j + " ");
            }
        }
        else if (odd==true&even==true){
            System.out.print("\nEven and odd numbers paired\n");
            
            for(int j=this.num; j<=10; j+=2){
                try {
                    Thread.sleep(600);
                    } catch (InterruptedException ex) {
                    System.out.println("The sleeping has been interruped!");
                    }
                
                System.out.print(j + " " + (j+1)+" | ");
            }
        }
    }
}

class OddEvenNums {
    public static void main(String[] args) {
        Counter odd = new Counter(1,true,false);
        Counter evenodd = new Counter(1,true,true);
        
        Thread oddThread = new Thread(odd);
        Thread evenOddThread = new Thread(evenodd);
        oddThread.start();
        evenOddThread.start();

    }
}

Basically this code just has two threads that either print out the odd numbers from 1-10 or print out the odd and the even numbers paired

However the output comes out like

run:

Odd numbers

Even and odd numbers paired
1 3 5 7 9 1 2 | 3 4 | 5 6 | 7 8 | 9 10 |

Instead of what I was hoping for which would be

run:

Odd numbers

1 3 5 7 9

Even and odd numbers paired
 1 2 | 3 4 | 5 6 | 7 8 | 9 10 |

I am confused about what I have done wrong to cause it to be outputted like this

Both Threads are running in parallel, not one after another (that's the purpose of Threads in the first place). That's why their output gets mixed up.

Trying to explain the output that you're seeing: The "odd" Thread gets a tiny bit of a head start, letting it print "Odd numbers" first. Then the "oddeven" Thread kicks in and prints "Event and odd numbers paired". Next thing, "oddeven" sleeps for 600 milliseconds (= half an eternity in computer time), giving "odd" all the time it needs to complete printing its sequence. Once the 600ms are elapsed, "oddeven" kicks back in and prints its own sequence (delaying another 600ms between each pair, but that doesn't really matter any more, as "odd" has long completed).

This is by no means deterministic, though. Meaning, if you run the program a couple of times you might see completely different sequences of String output.

The output is totally expected, although it is a bit random in what order exactly stuff happens. What is happening here is:

oddThread writes "Odd numbers"

evenOddThread writes "Even and odd numbers paired"

oddThread writes "1 3 5 7 9" (without newline)

evenOddThread writes "1 2 | 3 4 | 5 6 | 7 8 | 9 10 |"

So, you did nothing wrong per se. But you didn't think about what would happen when you run both threads concurrently. Either don't do that (wait for oddThread to be finished before starting evenOddThread, by calling oddThread.join()), or put some synchronization in there to make sure the output is written atomically. You are somewhat lucky to get the output you got. I could also have:

  • Just worked, until it randomly doesn't
  • mixed the output up even worse, like 1 1 2 3 | 3 4 5 7 | 5 6 9 | 7 8 | 9 10 |
  • put evenOddThread output above oddThread (probably unlikely but there is no guarantuee for how the threads get scheduled)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM