我目前正在学习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]
我不明白为什么会发生这种情况?设置优先级能够帮助解决吗?