ThreadGroup in Java

I am currently learning basics of Threads in Java and I am trying to write a simple Thread Group program. I wrote it same as tutorial website though i'm getting different type of output. Below is my code for which i'm getting different output.

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();
    }

}

I am getting Output :

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]

The output should be like :

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] 

i am not able to understand why this happening? setting Priority can help with it?


You can't predict the order of executions of your threads even with a level of priority. You have no control on the scheduling. It's your OS which decides.

A good book about concurrency in Java : Java concurrency in practice

链接地址: http://www.djcxy.com/p/31772.html

上一篇: 卡夫卡到zookeeper命令产生错误

下一篇: Java中的ThreadGroup