下面的代码在我的idea中输出主线程和分线程总是主线程一次,分线程一次
如下:
源代码如下:
class HelloThread extends Thread{
public HelloThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0){
System.out.println(Thread.currentThread()getName() + ":" + Thread.currentThread().getPriority() + ":" + i);
}
}
}
}
public class ThreadMethodTest {
public static void main(String[] args) {
HelloThread h1 = new HelloThread("线程一");
// h1.setName("线程一");
//设置分线程的优先级
// h1.setPriority(Thread.MAX_PRIORITY);
//设置主线程的优先级
// Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
h1.start();
//给主线程命名
Thread.currentThread().setName("主线程");
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + "::::::::::" + i);
}
}
System.out.println(h1.isAlive());
}
}
但在朋友的电脑上运行却不一样,如下:
各位大能,靠你们了!
谢谢
线程的优先级越高并不代表他一定会先执行,jvm只能建议cpu优先执行优先级高的,最终决定权还是在cpu上