Closed. This question needs debugging details。它当前不接受答案。












想要改善这个问题吗?更新问题,以便将其作为on-topic用于堆栈溢出。

5年前关闭。



Improve this question




我目前正在学习Java中线程的基础知识,并且正在尝试编写一个简单的线程组程序。我写的是与教程网站相同的内容,尽管我得到了不同类型的输出。以下是我得到不同输出的代码。
public class ThreadGroupDemo implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
        // get the name of the current thread.
    }

    public static void main(String[] args) {
        ThreadGroupDemo runnable = new ThreadGroupDemo();
        ThreadGroup tg1 = new ThreadGroup("Parent Group");
        // Creating thread Group.

        Thread t1 = new Thread(tg1, new ThreadGroupDemo(), "one");
        t1.start();
        t1.setPriority(Thread.MAX_PRIORITY);

        Thread t2 = new Thread(tg1, new ThreadGroupDemo(), "second");
        t2.start();
        t2.setPriority(Thread.NORM_PRIORITY);

        Thread t3 = new Thread(tg1, new ThreadGroupDemo(), "Three");
        t3.start();

        System.out.println("Thread Group name : " + tg1.getName());
        tg1.list();
    }

}

我正进入(状态
输出:
Thread Group name : Parent Group
Three
java.lang.ThreadGroup[name=Parent Group,maxpri=10]
    second
one
Thread[one,10,Parent Group]
    Thread[second,5,Parent Group]
    Thread[Three,5,Parent Group]

输出应该是这样的:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
    Thread[one,5,Parent ThreadGroup]
    Thread[two,5,Parent ThreadGroup]
    Thread[three,5,Parent ThreadGroup]

我不明白为什么会这样?设置优先级可以帮助您吗?

最佳答案

即使具有优先级,您也无法预测线程的执行顺序。您无法控制计划。取决于您的操作系统。

关于Java并发性的好书:Java concurrency in practice

10-07 19:31
查看更多