可以运用setPriority()方法来实行
测试程序如下:
public class DemoTestPriority extends Thread {
private String Threadname;
public String getThreadname() {
return Threadname;
}
public DemoTestPriority(String threadname) {
Threadname = threadname;
}
@Override
public void run() {
super.run();
System.out.println(this.getThreadname()+ "运行!");
}
public static void main(String[] args) {
//主线程
DemoTestPriority main= new DemoTestPriority("主线程");
DemoTestPriority demo1 = new DemoTestPriority("线程1");
Thread thread1 = new Thread(demo1);
DemoTestPriority demo2 = new DemoTestPriority("线程2");
Thread thread2 = new Thread(demo2);
//设置线程的优先级
//优先级越高,线程的运行越靠前。
thread1.setPriority2);//优先运行
thread2.setPriority(4);//稍后运行
main.setPriority(3);
main.start();
thread1.start();
thread2.start();
}
}
运行结果:
线程2运行!
主线程运行!
线程1运行!