目前,我正在学习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] 我不明白为什么会发生这种事?设定优先级能帮上忙吗?
发布于 2016-02-01 10:31:27
即使在优先级级别上,也无法预测线程的执行顺序。你无法控制日程安排。是你的操作系统决定了。
一本关于Java并发性的好书:https://rads.stackoverflow.com/amzn/click/com/0321349601
https://stackoverflow.com/questions/35128092
复制相似问题