优先级不准?你理解什么叫线程优先级吗?
线程你只要不告诉它等待,它是不会等其他线程先结束的。什么是线程,线程天生就是并行运行分支,哪怕你给它最低的优先级,那它也只是在同一时刻相比其他线程被执行的几率较低,而完全没有道理停下来等待。
如果你要让它等待,有很多办法,例如,最简单:
public class Test extends Thread {
private static Object lock = new Object();
public static void main(String[] args) {
try {
Test p1 = new Test();
Test p2 = new Test();
p1.setName("线程1");
p2.setName("线程2");
p1.setPriority(MAX_PRIORITY);
p2.setPriority(MIN_PRIORITY);
p1.start();
while (p1.getState() != Thread.State.TERMINATED);
p2.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
for (int i = 0; i <= 5; i++) {
System.out.println(getName() + " ");
}
}
}
public class PriorityTest extends Thread {
public static void main(String[] args) {
try {
PriorityTest p1 = new PriorityTest();
PriorityTest p2 = new PriorityTest();
p1.setName("线程1");
p2.setName("线程2");
p1.setPriority(MAX_PRIORITY);
p2.setPriority(MIN_PRIORITY);
p2.start();
p1.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
for (int i = 0; i <= 5; i++) {
System.out.println(getName() + " ");
}
}
}
是不是少了Test了..我这样运行起来正确的啊..是都先1再2的
把Priority 发出来看下..
看来还是没学到家,多看点书或者视频吧。