简体   繁体   English

Java 线程输出答案错误

[英]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基本上这段代码只有两个线程,要么打印出 1-10 的奇数,要么打印出成对的奇数和偶数

However the output comes out like然而 output 出来像

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.这就是为什么他们的 output 搞混了。

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.试图解释您所看到的 output:“奇数”线程领先一步,让它首先打印“奇数”。 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.接下来,“oddeven”休眠 600 毫秒(= 计算机时间的半个永恒),给“odd” 提供完成打印其序列所需的所有时间。 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).一旦 600ms 过去了,“oddeven”就会重新开始并打印自己的序列(每对之间再延迟 600ms,但这不再重要,因为“odd”早就完成了)。

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.这意味着,如果您多次运行该程序,您可能会看到完全不同的字符串 output 序列。

The output is totally expected, although it is a bit random in what order exactly stuff happens. output 完全是意料之中的,尽管事情发生的顺序有点随机。 What is happening here is:这里发生的是:

oddThread writes "Odd numbers"奇数线程写“奇数”

evenOddThread writes "Even and odd numbers paired" evenOddThread 写入“偶数和奇数配对”

oddThread writes "1 3 5 7 9" (without newline)奇线程写“1 3 5 7 9”(没有换行符)

evenOddThread writes "1 2 | 3 4 | 5 6 | 7 8 | 9 10 |" evenOddThread 写入“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.要么不这样做(通过调用oddThread.join(),在启动evenOddThread 之前等待oddThread 完成),或者在其中放置一些同步以确保output 是原子写入的。 You are somewhat lucky to get the output you got.你有点幸运能得到你得到的 output。 I could also have:我还可以:

  • Just worked, until it randomly doesn't刚刚工作,直到它随机不
  • mixed the output up even worse, like 1 1 2 3 |将 output 混合得更糟,例如 1 1 2 3 | 3 4 5 7 | 3 4 5 7 | 5 6 9 | 5 6 9 | 7 8 | 7 8 | 9 10 | 9 10 |
  • put evenOddThread output above oddThread (probably unlikely but there is no guarantuee for how the threads get scheduled)将 evenOddThread output 放在oddThread 之上(可能不太可能,但无法保证线程如何调度)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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