本文介绍了线程中的输出不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class MainClass {
    public static void main(String args[]){
        NewThread ob1 = new NewThread("One");
        NewThread ob2 = new NewThread("Two");
        NewThread ob3 = new NewThread("Three");

        try{
            System.out.println("Waiting for threads to finish.");
            ob1.t.join();
            ob2.t.join();
            ob3.t.join();
        } catch (InterruptedException e){
            System.out.println("Main thread interrupted");
        }

        System.out.println("Exiting main thread.");
    }
}
class NewThread implements Runnable {
    Thread t;

    NewThread(String name){
        t = new Thread(this, name);
        System.out.println("New thread: " + t);
        t.start();
    }

    public void run(){
        try{
            for(int i=3; i>0; i--){
                System.out.println(t.getName() + ": " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e){
            System.out.println(t.getName() + " interrupted.");
        }
        System.out.println("Exiting " + t.getName());
    }
}

上面的代码旨在提供此输出:

The code above was intended to give this output:

新线程:线程[1,5,main]
新线程:Thread [Two,5,main]
新线程:线程[Three,5,main]
等待线程完成.
一:3
2:3
三:3
一:2
二:2
三:2
一:1
二:1
三:1
退出一个
退出两个
退出三个
退出主线程.

New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Waiting for threads to finish.
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
Exiting One
Exiting Two
Exiting Three
Exiting main thread.

相反,它给出的输出如下:

Instead it is giving output as follows:

新线程:线程[1,5,main]
新线程:Thread [Two,5,main]
一:3
新线程:线程[Three,5,main]
2:3
等待线程完成.
三:3
三:2
一:2
二:2
三:1
二:1
一:1
退出两个
退出三个
退出一个
退出主线程.

New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
One: 3
New thread: Thread[Three,5,main]
Two: 3
Waiting for threads to finish.
Three: 3
Three: 2
One: 2
Two: 2
Three: 1
Two: 1
One: 1
Exiting Two
Exiting Three
Exiting One
Exiting main thread.

请帮助我更正代码.

推荐答案

由于您正在执行多线程处理,因此无法保证在不赋予线程比其他线程更高的优先级的情况下,将运行什么顺序的线程.仅仅因为您希望输出按特定顺序排列,IMO就打败了多线程的目的.您可能还没有生成线程作为开始.对于真正的"多线程,我希望您的输出像您显示的那样混合在一起,但同样不能保证.

Since you're doing multithreading, there is no guarantee what order threads will run without giving a thread a higher priority over another. Just because your want your output to be in a certain order, IMO, defeats the purpose of multithreading. You may as well not have spawned a threads to begin with. For "true" multithreading, I would expect your outputs to be mingled like you are showing, but again that is not guaranteed.

这篇关于线程中的输出不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:57