Java中的ThreadGroup

前端之家收集整理的这篇文章主要介绍了Java中的ThreadGroup前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前正在学习 Java中的Threads基础知识,我正在尝试编写一个简单的Thread Group程序.虽然我得到了不同类型的输出,但我和教程网站一样写了它.下面是我的代码,我得到不同的输出.
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,"second");
        t2.start();
        t2.setPriority(Thread.NORM_PRIORITY);

        Thread t3 = new Thread(tg1,"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,Parent Group]

输出应该像:

one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
    Thread[one,Parent ThreadGroup]
    Thread[two,Parent ThreadGroup]
    Thread[three,Parent ThreadGroup]

我无法理解为什么会这样?设置优先级可以帮助吗?

解决方法

即使具有优先级,您也无法预测线程的执行顺序.您无法控制计划.这是你的OS决定.

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

猜你在找的Java相关文章